java對象的複製,淺複製、深複製__java

來源:互聯網
上載者:User

淺複製:將一個對象複製後,基礎資料型別 (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();  }  

要實現深複製,需要採用流的形式讀入當前對象的二進位輸入,再寫出位元據對應的對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.