2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Please explain the difference between deep copy and shallow copy in Java.
In Java, Deep Copy and Shallow Copy are two ways of copying objects, and their behaviors when copying objects are fundamentally different.
A shallow copy is a new object created and then the non-static fields of the current object are copied to the new object. If the field is of value type, a bit-by-bit copy is performed on the field; if the field is of reference type, the reference is copied but the referenced object is not copied. Therefore, the original object and its copy refer to the same object.
In Java, this can be achieved byCloneable
Interface and rewriteclone()
method to achieve shallow copy.Object
In the classclone()
method can achieve shallow copy.
class Original implements Cloneable { | |
private int[] nums; | |
public Original() { | |
nums = new int[5]; | |
} | |
public void setNums(int[] nums) { | |
this.nums = nums; | |
} | |
public Object clone() throws CloneNotSupportedException { | |
return super.clone(); | |
} | |
} |
In this example,nums
is a reference type. IfOriginal
The object is shallowly copied, so thenums
and the original objectnums
will point to the same array object.
A deep copy not only copies the object itself, but also recursively copies all reference type member variables contained in the object, which means that the copy and the original object do not share any reference type member variables. Modifying any member variable of one object will not affect the other object.
In Java, implementing a deep copy usually requires manually writing code to ensure that all member variables of reference types are copied appropriately.
class DeepCopied implements Cloneable { | |
private int[] nums; | |
public DeepCopied() { | |
nums = new int[5]; | |
} | |
public void setNums(int[] nums) { | |
this.nums = nums; | |
} | |
@Override | |
public Object clone() throws CloneNotSupportedException { | |
DeepCopied copied = (DeepCopied) super.clone(); | |
copied.nums = nums.clone(); // 对引用类型的成员变量也进行拷贝 | |
return copied; | |
} | |
} |
In this example,nums
The array is also copied, so the original object and the copy are not shared.nums
Array.
The choice of using deep copy or shallow copy depends on the specific application scenario and requirements.
What is an anonymous inner class in Java? What are its applications?