Technology Sharing

Please explain the difference between deep copy and shallow copy in Java. What is an anonymous inner class in Java? What are its application scenarios?

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.

Shallow Copy

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 byCloneableInterface and rewriteclone()method to achieve shallow copy.ObjectIn 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,numsis a reference type. IfOriginalThe object is shallowly copied, so thenumsand the original objectnumswill point to the same array object.

Deep Copy

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,numsThe array is also copied, so the original object and the copy are not shared.numsArray.

Summarize

  • Shallow copyThe object itself and its non-static fields are copied, but referenced objects are not copied.
  • Deep CopyNot only the object itself and its non-static fields are copied, but also all member variables of reference type are recursively copied.

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?