`
lihengzkj
  • 浏览: 44181 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

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

阅读更多
克隆的主对象:(重写了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。
分享到:
评论
1 楼 yimengyuanyun 2013-02-01  
浅度克隆后,里面的对象是不是还是指向原来的对象,所以tcb.getChild()==tcb1.getChild()为true,这样理解对伐?

相关推荐

Global site tag (gtag.js) - Google Analytics