标签:
一、对象的浅克隆
对象浅克隆要注意的细节:
Person类中,引用了Address类,我们通过浅克隆来观察结果:
class Address implements Cloneable ,Serializable{
String city;
public Address(String city) {
super();
this.city = city;
}
}
public class Person implements Cloneable ,Serializable{
int id;
String name;
Address address;
public Person(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
public String toString(){
return "编号:"+ this.id+" 姓名:"+ this.name+" 地址:"+ address.city;
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
当我们克隆了p1,然后更改p2的city,p1和p2都改变了,也就是上边所说的第3点:对象的浅克隆就是克隆一个对象的时候,如果被克隆的对象中维护了另外一个类的对象,这时候只是克隆另外一个对象的地址,而没有把另外一个对象也克隆一份。
二、对象深拷贝
对象的深克隆就是利用对象的输入输出流把对象先写到文件上,然后再读取对象的信息这个过程就称作为对象的深克隆
深复制把要复制的对象所引用的对象都复制了一遍
public class Demo2 { public static void main(String[] args) throws Exception { Address address=new Address("上海"); Person person1=new Person(1,"萧山",address); writeObj(person1); Person person2=readObj(); person2.address.city="河南"; System.out.println(person1); System.out.println(person2); } public static void writeObj(Person p) throws Exception{ File file=new File("D:\\obj.txt"); FileOutputStream fileOutputStream=new FileOutputStream(file); ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(p); } public static Person readObj() throws Exception { File file=new File("D:\\obj.txt"); FileInputStream fileInputStream=new FileInputStream(file); ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream); return (Person) objectInputStream.readObject(); } }
当我们克隆了p1,然后更改p2的city,p1就不会改变了,也就是把Address也复制了一份。
标签:
原文地址:http://www.cnblogs.com/lyjs/p/5076900.html