Java中的拷貝分為深拷貝和淺拷貝,兩者實現的方法有所不同:
淺拷貝
淺拷貝是指在拷貝對象時,只復制對象的基本數據類型、對象引用等,而不拷貝引用指向的對象或元素。實現淺拷貝有以下兩種方法:
1.使用Object類的clone方法
public class Test implements Cloneable { private int id; private Listlist; public Test(int id, List list) { this.id = id; this.list = list; } public Object clone() { Test o = null; try { o = (Test) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return o; } }
2.使用Copy構造方法
public class Test { private int id; private Listlist; public Test(Test t) { this.id = t.id; this.list = t.list; } }
深拷貝
深拷貝是指在拷貝對象時,會遞歸地拷貝對象引用指向的對象或元素。實現深拷貝有以下兩種方法:
1.使用Java序列化和反序列化
public class Test implements Serializable { private int id; private Listlist; public Test(int id, List list) { this.id = id; this.list = list; } public Object deepClone() throws IOException, ClassNotFoundException { ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(this); ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi = new ObjectInputStream(bi); return oi.readObject(); } }
2.使用自定義方法遞歸拷貝對象引用指向的對象或元素
public class Test { private int id; private Listlist; public Test deepClone() { Test o = new Test(this.id, new ArrayList<>()); for (String s : this.list) { o.list.add(s); } return o; } }