Java Deep Clone Shallow Clone 深複製和淺複製

來源:互聯網
上載者:User
Java Deep Clone Shallow Clone 深複製和淺複製

為什麼要用Clone?

Java通過傳遞控制代碼來傳參數。當你傳遞一個對象時實際上是傳遞了一個方法外的物件控點,因此當你對方法內的控制代碼做任何改變的時候實際上就是修改了方法外的對象。此外:

Aliasing happens automatically during argument passing. 別名操作在對象傳遞過程中自動進行

There are no local objects, only local handles. 沒有局部的對象,只有局部的控制代碼

Handles have scopes, objects do not. 控制代碼有範圍限制,對象沒有

Object lifetime is never an issue in Java. Java中對象的生命週期從來不是一個問題

There is no language support (e.g. const) to prevent objects from being modified (to prevent negative effects of aliasing). 沒有語言方面的保證使對象免於修改。

同時java是按值傳遞未經處理資料,但對於對象傳遞的則是引用。但我們有時候會希望有一個local的對象而不必修改外面對象,這樣就是我們說的clone了。

Java的預設裡是淺複製,也就是只是對象的一個簡單clone。但是當一個class裡包含複雜的對象時,比如一個School裡有teacher和student,那麼該就需要深度clone。簡單的說,用資料庫的角度,如果要用“cascading delete”的那麼就要用深複製,否則就是淺複製。 一個深複製的例子如下:

//: DeepCopy.java// Cloning a composed objectclass DepthReading implements Cloneable {  private double depth;  public DepthReading(double depth) {     this.depth = depth;  }  public Object clone() {    Object o = null;    try {      o = super.clone();    } catch (CloneNotSupportedException e) {      e.printStackTrace();    }    return o;  }}class TemperatureReading implements Cloneable {  private long time;  private double temperature;  public TemperatureReading(double temperature) {    time = System.currentTimeMillis();    this.temperature = temperature;  }  public Object clone() {    Object o = null;    try {      o = super.clone();    } catch (CloneNotSupportedException e) {      e.printStackTrace();    }    return o;  }}class OceanReading implements Cloneable {  private DepthReading depth;  private TemperatureReading temperature;  public OceanReading(double tdata, double ddata){    temperature = new TemperatureReading(tdata);    depth = new DepthReading(ddata);  }  public Object clone() {    OceanReading o = null;    try {      o = (OceanReading)super.clone();    } catch (CloneNotSupportedException e) {      e.printStackTrace();    }    // Must clone handles:    o.depth = (DepthReading)o.depth.clone();    o.temperature =       (TemperatureReading)o.temperature.clone();    return o; // Upcasts back to Object  }}public class DeepCopy {  public static void main(String[] args) {    OceanReading reading =       new OceanReading(33.9, 100.5);    // Now clone it:    OceanReading r =       (OceanReading)reading.clone();  }} ///:~ 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.