Java中深拷貝和淺拷貝的實現方式如下:
Object
類的clone()
方法實現,需要實現Cloneable
接口,并重寫clone()
方法。示例代碼如下: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;
}
}
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);
}
}
以上是兩種常見的深拷貝和淺拷貝的實現方式,根據具體的需求和場景選擇合適的方式。