淺複製:將一個對象複製後,基礎資料型別 (Elementary Data Type)的變數都會重新建立,而參考型別,指向的還是原對象所指向的。
深複製:將一個對象複製後,不論是基礎資料型別 (Elementary Data Type)還有參考型別,都是重新建立的。簡單來說,就是深複製進行了完全徹底的複製,而淺複製不徹底。
此處,寫一個深淺複製的例子:
public class Prototype implements Cloneable, Serializable {
private static final long serialVersionUID = 1L; private String string; private SerializableObject obj; /* 淺複製 */ public Object clone() throws CloneNotSupportedException { Prototype proto = (Prototype) super.clone(); return proto; } /* 深複製 */ public Object deepClone() throws IOException, ClassNotFoundException { /* 寫入當前對象的二進位流 */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); /* 讀出二進位流產生的新對象 */ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return ois.readObject(); }
要實現深複製,需要採用流的形式讀入當前對象的二進位輸入,再寫出位元據對應的對象。