读书人

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

发布时间: 2012-10-30 16:13:36 作者: rapoo

深度克隆和浅度克隆的总结
克隆的主对象:(重写了clone方法)

public class TestClonBean implements Cloneable,Serializable{private String name;private int age;private String sex;@Overrideprotected TestClonBean clone(){TestClonBean bean = null;try {bean = (TestClonBean) super.clone();} catch (CloneNotSupportedException e) {// TODO Auto-generated catch blocke.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 blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.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。

读书人网 >编程

热点推荐