深拷贝clone

直接上代码:之前写过一个序列化拷贝,他两者的区别是内存到内存(clone)、内存到物理储存,或者流

        测试类两个:分析都在代码里

public class StringCloneTest01 implements Cloneable{
	String str = "2";
	Integer integer = new Integer(300);
	StringCloneTest02 c2;




    @Override
    //public  返回值都是可以变的返回值只能是子类,public遵循重写的规定
	public StringCloneTest01 clone() throws CloneNotSupportedException {

		//这里一定要重设引用的值,否则不能clone成功引用

		StringCloneTest01 clone = (StringCloneTest01) super.clone();
		clone.c2 = (StringCloneTest02) clone.c2.clone();
		return (StringCloneTest01) clone;
	}

}



class StringCloneTest02 implements Cloneable{
	 int a = 5;
	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
	
}

          测试方法

public static void test02() throws CloneNotSupportedException {
		//listclone失败,其中的泛型不会被clone
		ArrayList<StringCloneTest01> list = new ArrayList<StringCloneTest01>();
		list.add(new StringCloneTest01("as"));
		list.add(new StringCloneTest01("sasdsad"));
		list.add(new StringCloneTest01(new StringCloneTest02()));
		ArrayList<StringCloneTest01> list2 = (ArrayList) list.clone();
		list.get(2).c2 = new  StringCloneTest02();
		System.out.println(list == list2);//false
		System.out.println(list.get(2).c2 == list2.get(2).c2);//true
		
		
		//************************测试单个的clone
		System.out.println("**********************");
		StringCloneTest01 c1 = new StringCloneTest01(new StringCloneTest02());
		StringCloneTest01 c1_2 = c1.clone();
		c1_2.c2.a = 56;
		c1.str = "5";
//		c1.integer = 5;
		System.out.println(c1 == c1_2);//false
		System.out.println(c1.c2 == c1_2.c2);//false
		
		//因为str也没有实现clone,具有它本身常量的特性
		System.out.println(c1.str == c1_2.str);//false
		System.out.println(c1.integer == c1_2.integer);//true,修改值变为false,值互不影响
		System.out.println(c1.integer);
		System.out.println(c1_2.integer);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值