java - 深拷贝 浅拷贝
一.定义
1.浅拷贝
1.定义
浅拷贝只复制对象的引用,不复制引用指向的实际对象。对基本数据类型复制值,对引用类型的值复制其引用。
2.实现方法
通过重写Object类的clone()方法,并让类实现Cloneable接口
3.代码示例
// 浅拷贝
public class Student implements Cloneable{int age;String name;@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}
2.深拷贝
1.定义
深拷贝不止复制对象本身,还递归复制对象中所有引用的对象,使新对象和旧对象之间完全独立
2.实现方法
1.让所有嵌套的引用类型也实现 Cloneable
接口并重写 clone()
,在顶层对象的 clone()
中递归调用嵌套对象的 clone()
。
2.通过序列化将对象写入流,再从流中读取,序列化方式简单易用,但性能较低
3.代码示例
1.递归调用
class Address implements Cloneable {String city;public Address(String city) {this.city = city;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}class Person implements Cloneable {String name;Address addr; public Person(String name, Address addr) {this.name = name;this.addr = addr;}@Overrideprotected Object clone() throws CloneNotSupportedException {Person copy = (Person) super.clone();copy.addr = (Address) this.addr.clone(); return copy;}
}
2.序列化
class Address implements Serializable {String city;public Address(String city) {this.city = city;}
}class Person implements Serializable {String name;Address addr;public Person(String name, Address addr) {this.name = name;this.addr = addr;}Person deepCopy() throws Exception {// 写入字节流ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(bos);oos.writeObject(this);// 将字节序列恢复为新对象ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));return (Person) ois.readObject();}
}