In the following code, why
//对引用的对象也进行复制
o.p=(Professor)p.clone();
Is it possible to achieve deep copy?
class Professor implements Cloneable
{
String name;
int age;
Professor(String name,int age)
{
this.name=name;
this.age=age;
}
public Object clone()
{
Object o=null;
try
{
o=super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println(e.toString());
}
return o;
}
}
public class Student implements Cloneable
{
String name;
int age;
Professor p;
Student(String name,int age,Professor p)
{
this.name=name;
this.age=age;
this.p=p;
}
public Object clone()
{
Student o=null;
try
{
o=(Student)super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println(e.toString());
}
//对引用的对象也进行复制
o.p=(Professor)p.clone();
return o;
}
public static void main(String[] args)
{
Professor p=new Professor("wangwu",50);
Student s1=new Student("zhangsan",18,p);
Student s2=(Student)s1.clone();
s2.p.name="lisi";
s2.p.age=30;
//学生1的教授不 改变。
System.out.println("name="+s1.p.name+","+"age="+s1.p.age);
System.out.println("name="+s2.p.name+","+"age="+s2.p.age);
}
}
This just appears to be "deep copy" on the surface. In fact, neither Student nor Professor implements deep copy.
You add several outputs to the main method:
You can see that the names of s1 and s2 are still "==". When p.name is not set, their names are also "==", so no deep copy is implemented.
When you set s2.p.name, s2.p.name points to the address of another string constant, so (s1.p.name == s2.p.name); //false
This is a shallow copy, which can only copy basic data types. To copy an object member variable, you need to call the clone method of the member variable. This is how I understand it. Multiple shallow copies can achieve deep copy
It is not a deep copy. You can try to clone it. It means that the String is still referenced to the original one
professor.name
与原来的professor.name
是==
The default implementation of the jdk clone method is value copy. For basic types, it is to copy the value. For references, it is the address pointed by the copy reference.
So if there is no
o.p=(Professor)p.clone();
this code, then the p of the original object and the clone object refer to the same Professor object, which is a shallow copy.