Difference between deep copy and shallow copy
After an instance has been copied, in the newly generated instance, the memory address of the member variable of reference type has not been changed, which is the same as the memory address of the original instance. This is a shallow copy Otherwise, if the memory address of the reference type member variable of the original instance is different, it is a deep copy. Member variables of basic types are not considered here.
The following is a Java example to facilitate the understanding of the concept:
package com.example.butterknife_compiler;
/**
* Created by Administrator on 2018/3/26.
*/
public class OutClass implements Cloneable {
InnerClass innerClass;
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
OutClass outClass=new OutClass();
outClass.innerClass=new OutClass().new InnerClass();
//Here is a new instance of clone
OutClass outClass2= (OutClass) outClass.clone();
//Comparing the referential variables of outClass and outClass2 -- > innerclass
System.out.println(outClass.innerClass==outClass2.innerClass);
}
public class InnerClass implements Cloneable {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
}
If the address of the reference variable innerClass in the two instances is the same, it is a shallow copy. Let's look at printing:
So the question is, how can we make deep copy? Simply, let's continue clone with our referential member variable
public class OutClass implements Cloneable {
InnerClass innerClass;
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
OutClass outClass=new OutClass();
outClass.innerClass=new OutClass().new InnerClass();
OutClass outClass2= (OutClass) outClass.clone();
//The point here is to let the referential member variable continue clone
outClass.innerClass= (InnerClass) outClass.innerClass.clone();
System.out.println(outClass.innerClass==outClass2.innerClass);
}
public class InnerClass implements Cloneable {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
}
Look at the execution results: