How to implement deep copy and shallow copy in Java?
The implementation methods for deep copy and shallow copy in Java are as follows:
- Item
- create an identical copy
- Capable of being cloned
- create a copy
public class MyClass implements Cloneable {
private int value;
private List<String> list;
public MyClass(int value, List<String> list) {
this.value = value;
this.list = list;
}
@Override
protected Object clone() throws CloneNotSupportedException {
MyClass clone = (MyClass) super.clone();
clone.list = new ArrayList<>(list);
return clone;
}
}
- Deep copy: A deep copy refers to creating a new object and then copying the values of all fields of the original object to the new object, including reference type fields. Deep copy requires manually recursively copying reference type fields. Example code is as follows:
public class MyClass {
private int value;
private List<String> list;
public MyClass(int value, List<String> list) {
this.value = value;
this.list = list;
}
public MyClass(MyClass other) {
this.value = other.value;
this.list = new ArrayList<>(other.list);
}
}
The above are two common ways to implement deep copy and shallow copy, choose the appropriate method based on specific needs and scenarios.