直接上代码:之前写过一个序列化拷贝,他两者的区别是内存到内存(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);
}