深度克隆和浅度克隆的总结

克隆的主对象:(重写了clone方法)

public class TestClonBean implements Cloneable,Serializable{
private String name;
private int age;
private String sex;
@Override
protected TestClonBean clone(){
TestClonBean bean = null;
try {
bean = (TestClonBean) super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bean;
}
省略get/set方法……
}

克隆的从属对象:

public class TestCloneChildBean implements Cloneable,Serializable{
private String cname;
private String csex;
private int cage;
省略get/set方法……
}

深度克隆的工具类:
(深度克隆的原理:把对象序列化输出到内存,然后从内存中把序列化的byte[]取出来,进行反序列化获取对象)

public class DeepCloneBean {
public static Object getObject(Object obj){
Object cloneobj = null;
ByteArrayInputStream bin = null;
ByteArrayOutputStream bout = null;
try {
//把对象对到内存中去
bout = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bout);
oos.writeObject(obj);
oos.close();
//把对象从内存中读出来
ByteArrayInputStream bais = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
cloneobj = ois.readObject();
ois.close();
return cloneobj;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

测试:

public class TestClone {
public static void main(String []args){
//浅度克隆
TestCloneChildBean tcc = new TestCloneChildBean();
TestCloneChildBean tcc1 = tcc.clone();
System.out.println(tcc==tcc1);//result:false;
TestClonBean tcb = new TestClonBean();
tcb.setChild(tcc);
TestClonBean tcb1 = tcb.clone();
System.out.println(tcb==tcb1);//result:false;
System.out.println(tcb.getChild()==tcb1.getChild());//result:true;
System.out.println("*****************浅度克隆完************");
//深度克隆
TestClonBean tt1 = new TestClonBean();
TestCloneChildBean tc1 = new TestCloneChildBean();
tt1.setChild(tc1);
TestClonBean tcbclone = (TestClonBean) DeepCloneBean.getObject(tt1);
System.out.println(tt1==tcbclone);//result:false;
System.out.println(tt1.getChild()==tcbclone.getChild());//result:false;
}
}

总结:
不管是深度克隆还是浅度的克隆其实都是产生了一个新的对象。所以我们在比较克隆对象和源对象的时候返回是false。而深度克隆和浅度的克隆的区别在于:浅度克隆的对象只会克隆普通属性,不会克隆对象属性。而深度克隆就会连对象属性一起克隆。所以我们在对比深度克隆中的tt1.getChild()==tcbclone.getChild()时,返回是false。而浅度克隆时返回true。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值