对象深度拷贝

[b]利用序列化与反序列化对对象进行深度复制[/b]


public class Student implements Serializable {

private String name;
private String tel;
private int age;

//set and get.....
}

public class Teacher implements Serializable {

private String name;
private int age;
private List<Student> stuList;

//set and get....

}

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class Test {


public static void main(String[] args) {
Student s1 = new Student();
s1.setName("Wang");
s1.setAge(25);
s1.setTel("110");
Student s2 = new Student();
s2.setName("Li");
s2.setAge(35);
s2.setTel("119");


Teacher t = new Teacher();
t.setName("Zhang");
t.setAge(50);
List<Student> stuList = new ArrayList<Student>();
stuList.add(s1);
stuList.add(s2);
t.setStuList(stuList);
System.out.println("t: "+t);
System.out.println("s1: "+s1);
System.out.println("s2: "+s2);
System.out.println("after clone--------------");
Teacher t2 = (Teacher) depthClone(t);
System.out.println("t2: "+t2);
System.out.println("t: "+t);

Student s3 = t2.getStuList().get(0);
Student s4 = t2.getStuList().get(1);
System.out.println("s3: "+s3);
System.out.println("s1: "+s1);
System.out.println("s4: "+s4);
System.out.println("s2: "+s2);

System.out.println("after change--------------");
t2.setAge(55);
t2.setName("Zhao");

System.out.println("t2 Name: "+t2.getName()+" t2 age"+t2.getAge());
System.out.println("t Name: "+t.getName()+" t age"+t.getAge());

}

private static Object depthClone(Object srcObj){
Object cloneObj = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(out);
oo.writeObject(srcObj);

ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream oi = new ObjectInputStream(in);
cloneObj = oi.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return cloneObj;
}

}


输入结果:
t: jame.jsp.bean.Teacher@affc70
s1: jame.jsp.bean.Student@1e63e3d
s2: jame.jsp.bean.Student@1004901
after clone--------------
t2: jame.jsp.bean.Teacher@1f14ceb
t: jame.jsp.bean.Teacher@affc70
s3: jame.jsp.bean.Student@f0eed6
s1: jame.jsp.bean.Student@1e63e3d
s4: jame.jsp.bean.Student@1d05c81
s2: jame.jsp.bean.Student@1004901
after change--------------
t2 Name: Zhao t2 age55
t Name: Zhang t age50

*采用些方法做深度拷贝时,要求所有对象implements Serializable,否则报java.io.NotSerializableException异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值