clone
使用Object.clone() 创建出一个和原对象内容一样,地址不一样的对象
浅拷贝
实现Cloneable接口,重写clone方法,调用父类的clone方法,将返回值类型强转成本类类型
@Datapublic class Person implements Cloneable{private String name;private int age;private Children child;@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}@Overridepublic Person clone() throws CloneNotSupportedException {return (Person) super.clone();}}
浅拷贝的缺点:
拷贝出来的对象的引用类型的成员变量 child 是同一个引用
clone的深拷贝实现:
@Overridepublic Person clone() throws CloneNotSupportedException {Person clone = (Person) super.clone();clone.setChild(child.clone());return clone;}
IO实现深拷贝
// Person需要实现Serializable@Overridepublic Person clone() {try {//1. 创建ByteArrayOutputStream,将数据可以转换成字节ByteArrayOutputStream bout = new ByteArrayOutputStream();//2. 创建ObjectOutputStream,关联ByteArrayOutputStreamObjectOutputStream out = new ObjectOutputStream(bout);//3. 使用ObjectOutputStream的writeObject,读取要复制的对象out.writeObject(this);//4. 使用ByteArrayInputStream读取ByteArrayOutputStream的转换的对象字节数据ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());//5. 创建ObjectInputStream读取对象字节数据,创建新的对象ObjectInputStream in = new ObjectInputStream(bin);Person clone = (Person) in.readObject();return clone;} catch (Exception e) {e.printStackTrace();return null;}}
