為什麼要用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(); }} ///:~ |