在 Java 中,对象的拷贝可以分为深拷贝和浅拷贝两种:
浅拷贝(Shallow Copy)
浅拷贝是指只复制对象本身,而不复制对象引用的对象。也就是说,新对象和原对象共享同一个引用对象。
实现浅拷贝的方法:
-
使用
clone()方法:Java 中的
clone()方法可以用来实现浅拷贝。但是,为了使对象支持clone()方法,该对象必须实现Cloneable接口,并且重写clone()方法。class Student implements Cloneable { private String name; private int age; // 构造方法和其他方法 // 实现 clone() 方法 @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }使用
clone()方法进行拷贝:try { Student original = new Student("Alice", 20); Student copy = (Student) original.clone(); // 此时 original 和 copy 是两个不同的对象,但是它们的 name 和 age 属性引用的是同一个对象 } catch (CloneNotSupportedException e) { e.printStackTrace(); } -
使用复制构造函数(如果定义了):
如果类中提供了复制构造函数,可以用来实现浅拷贝。
class Student { private String name; private int age; // 复制构造函数 public Student(Student other) { this.name = other.name; this.age = other.age; } }使用复制构造函数进行拷贝:
Student original = new Student("Bob", 25); Student copy = new Student(original); // 此时 original 和 copy 是两个不同的对象,但是它们的 name 和 age 属性引用的是同一个对象
深拷贝(Deep Copy)
深拷贝是指不仅复制对象本身,还复制对象引用的所有对象,因此新对象和原对象引用的是不同的对象实例。
实现深拷贝的方法:
-
手动实现深拷贝:
手动实现深拷贝需要遍历对象引用的所有对象,并为每个对象创建一个新的实例。
class Student implements Cloneable { private String name; private int age; private Address address; // 构造方法和其他方法 // 实现 clone() 方法 @Override public Object clone() throws CloneNotSupportedException { // 浅拷贝 Student cloned = (Student) super.clone(); // 深拷贝 address 对象 cloned.address = (Address) address.clone(); return cloned; } } class Address implements Cloneable { private String city; private String street; // 构造方法和其他方法 // 实现 clone() 方法 @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }使用深拷贝:
try { Student original = new Student("Alice", 20, new Address("New York", "123 Street")); Student copy = (Student) original.clone(); // 此时 original 和 copy 是两个不同的对象,并且它们的 address 引用的是两个不同的 Address 对象实例 } catch (CloneNotSupportedException e) { e.printStackTrace(); } -
使用序列化和反序列化实现深拷贝:
利用 Java 的序列化机制,将对象写入一个流中,然后从流中读取出来,可以实现深拷贝。
import java.io.*; class Student implements Serializable { private String name; private int age; private Address address; // 构造方法和其他方法 // 实现深拷贝 public Student deepCopy() { try { // 将对象写入流中 ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); // 从流中读取对象 ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); return (Student) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); return null; } } } class Address implements Serializable { private String city; private String street; // 构造方法和其他方法 }使用序列化和反序列化实现深拷贝:
Student original = new Student("Alice", 20, new Address("New York", "123 Street")); Student copy = original.deepCopy(); // 此时 original 和 copy 是两个不同的对象,并且它们的 address 引用的是两个不同的 Address 对象实例
通过上述方式,可以根据需要选择浅拷贝或者深拷贝来复制对象,从而满足不同的需求。
2114

被折叠的 条评论
为什么被折叠?



