java的深拷贝和浅拷贝
来源:程序员人生 发布时间:2014-11-09 09:18:03 阅读次数:2529次
import java.util.*;
import java.io.*;
class User implements Serializable{
public String name;
public int age;
public User(String str,int num){
name=str;
age=num;
}
public String toString(){
return "Name:"+name+"
"+"Age:"+age;
}
}
class Test implements Cloneable,Serializable{
public int height;
public User user;
public Test(User u,int num){
user=u;
height=num;
}
public String toString(){
return user+"
"+"Height:"+height;
}
public Object clone(){
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
public class ArtTracer{
public static void main(String[] args){
Test obj1=new Test(new User("cjc",25),170);
Test obj2=(Test)obj1.clone();
obj1.user.age=30;
//Cloneable实现的浅拷贝例子
System.out.println(obj1);
System.out.println(obj2);
System.out.println("*****************");
//序列化实现的深拷贝
Test obj3=new Test(new User("hxh",24),168);
ByteArrayOutputStream bout=new ByteArrayOutputStream();
try {
ObjectOutputStream obj=new ObjectOutputStream(bout);
obj.writeObject(obj3);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
obj3.user.age=40;
try {
ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
Test obj4=(Test)in.readObject();
System.out.println(obj3);
System.out.println(obj4);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e){
e.printStackTrace();
}
}
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠