一、拷贝
(1)浅拷贝:被复制对象的所有值属性都含有与原来对象的相同,而所有的对象引用属性仍然指向原来的对象。
xep:简单的说就是被复制的对象里只有基本数据类型的属性。
class B{
String name;
String num;
}
(2)深拷贝:在浅拷贝的基础上,所有引用其他对象的变量也进行了clone,并指向被复制过的新对象。
class A{
String name;
String num;
B b;
}
二、测试
public static void main(String[] args) throws CloneNotSupportedException {
MyTest myTest = new MyTest();
B b1=new B("xq","497");
A a1 = new A("COCO","123",b1);
A a2=(A)a1.clone();
System.out.println(a1.equals(a2));
System.out.println(a1);
a2.getB().name="coco2";
System.out.println(a2);
System.out.println(a1);
}
结果:
三、操作
(1)浅复制:
class A extends Object implements Cloneable{
String name;
String num;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
(2)深复制
class A implements Cloneable{
String name;
String num;
B b;
@Override
protected Object clone() throws CloneNotSupportedException {
Object obj=super.clone();
B b=((A)obj).getB();//准备要复制的b
((A)obj).setB((B)b.clone());
return obj;
}
}