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);
}
}
以上是两种常见的深拷贝和浅拷贝的实现方式,根据具体的需求和场景选择合适的方式。