Java中的对象复制有两种方式:浅复制和深复制。

  1. 浅复制:通过复制对象的引用,创建一个新的对象,新对象和原对象共享同一个引用类型的属性。修改新对象的引用类型属性会影响原对象的引用类型属性。可以使用Object类的clone()方法进行浅复制。

示例代码:

class Person implements Cloneable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person p1 = new Person("Alice", 20);
        Person p2 = (Person) p1.clone();
        System.out.println(p1 == p2); // false
        System.out.println(p1.equals(p2)); // true
    }
}
  1. 深复制:通过复制对象的引用类型属性,创建一个新的对象,新对象和原对象的引用类型属性是独立的。修改新对象的引用类型属性不会影响原对象的引用类型属性。可以通过实现Serializable接口进行深复制,或者手动编写复制方法。

示例代码:

import java.io.*;

class Person implements Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person deepClone() throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (Person) ois.readObject();
    }
}

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Person p1 = new Person("Alice", 20);
        Person p2 = p1.deepClone();
        System.out.println(p1 == p2); // false
        System.out.println(p1.equals(p2)); // false
    }
}

注意:要实现深复制,需要确保对象及其引用类型属性都实现Serializable接口,否则会抛出NotSerializableException异常。

java 对象复制

原文地址: https://www.cveoy.top/t/topic/iF8s 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录