2011-06-17 36 views
9

據我所知,方法clone()使我們能夠在Java中複製對象(無參考)。但我也讀過,副本很淺。那麼有什麼意義呢? clone()方法賦予我哪種能力,簡單的幫助不會?Java中的clone()方法

回答

21

區別在於您可以在不修改原始對象的情況下修改克隆對象。

Point p = new Point(1,2); 
Point p2 = p.clone(); 
Point p3 = p; 
p2.x = 5; 
p3.y = 7; 

p3的變化並反饋給p,而在p2的變化沒有。

讓我們看到的情況是怎樣的個人陳述(假設1257將對象)後:

Point p = new Point(1,2); 

      .-----. .-----. 
p -----> | x -+--> | 1 | 
      |  | '-----' 
      |  | .-----. 
      | y -+--> | 2 | 
      '-----' '-----' 


Point p2 = p.clone(); 

      .-----. .-----. .-----. 
p -----> | x -+--> | 1 | <--+- x | <----- p2 
      |  | '-----' |  | 
      |  | .-----. |  | 
      | y -+--> | 2 | <--+- y | 
      '-----' '-----' '-----' 

Point p3 = p; 

      .-----. .-----. .-----. 
p -----> | x -+--> | 1 | <--+- x | <----- p2 
      |  | '-----' |  | 
      |  | .-----. |  | 
p3 -----> | y -+--> | 2 | <--+- y | 
      '-----' '-----' '-----' 


p2.x = 5; 

      .-----. .-----. .-----. .-----. 
p -----> | x -+--> | 1 | | x -+--> | 5 | 
      |  | '-----' |  | '-----' 
      |  | .-----. |  | 
p3 -----> | y -+--> | 2 | <--+- y | <----- p2 
      '-----' '-----' '-----' 


p3.y = 7; 

      .-----. .-----. .-----. .-----. 
p -----> | x -+--> | 1 | | x -+--> | 5 | 
      |  | '-----' |  | '-----' 
      |  | .-----. |  | 
p3 -----> | y | | 2 | <--+- y | <----- p2 
      '--+--' '-----' '-----' 
       |  .-----. 
       '---> | 7 | 
        '-----' 
4

一個簡單的賦值就會爲對象創建一個別名。使用clone(),每個屬性成員也將在克隆對象中初始化。但是,如果屬性成員本身包含更多的對象,則不會複製這些對象。

7

賦值將實例的引用複製到變量。 A 克隆操作將克隆實例(併爲克隆分配一個引用)。

隨着分配,你會擁有多個變量指向一個對象,用克隆你必須持有多個對象的引用多個變量。

SomeCloneable a = new SomeCloneable(); 
SomeCloneable b = a;      // a and b point to the same object 

/* versus */ 

SomeCloneable a = new SomeCloneable(); 
SomeCloneable b = a.clone();    // a and b point to the different objects 
+0

`Cloneable`不作`的clone()`方法公開,雖然。您必須將`a`和`b`聲明爲`SomeCloneable`。 – 2011-06-17 11:32:57

+0

@PaŭloEbermann - 好,趕快,謝謝,我會糾正的! – 2011-06-17 11:34:09

3

淺拷貝是默認的對象。您可以覆蓋克隆以進行深層複製。

1

深入克隆,你必須實現Cloneable和覆蓋的clone()

public class MyClass implements Cloneable { 

private Object attr = new Object(); 

@Override 
public Object clone() throws CloneNotSupportedException { 
    MyClass clone = (MyClass)super.clone(); 
    clone.attr = new Object(); 
    return clone; 
} 

@Override 
public String toString() { 
    return super.toString()+", attr=" + attr; 
} 

public static void main(String[] args) throws Exception { 
    MyClass x = new MyClass(); 
    System.out.println("X="+x); 
    MyClass y = (MyClass)x.clone(); 
    System.out.println("Y="+y); 
} 

}

相關問題