2016-05-31 97 views
-3

這種使用clone的方式是正確的嗎?我每次都遇到運行時錯誤。也有人可以提出一種方法來寫這個類的複製構造函數嗎?如何克隆/複製我自己的類的實例?

public class Pair { 
    final StringBuffer x; 
    final StringBuffer y; 

    public Pair(StringBuffer x, StringBuffer y) { 
     this.x = x; 
     this.y = y; 
    } 

    public StringBuffer getX() { 
     return x; 
    } 

    public StringBuffer getY() { 
     return y; 
    } 

    public Pair clone() { 
     Pair p = new Pair(new StringBuffer(), new StringBuffer()); 
     try { 
      p = (Pair) super.clone(); 
     } catch (CloneNotSupportedException e) { 
      throw new Error(); 
     } 
     return p; 
    } 
} 
+0

哪裏'arraylist'在標題和標籤中提到? –

+0

爲什麼你有一個複製構造函數,當你忽略它的作用? – Tom

回答

3

拷貝構造函數:

public Pair(Pair other) { 
    this.x = new StringBuffer(other.x.toString()); 
    this.y = new StringBuffer(other.y.toString()); 
} 

您應該avoid using clone()

  • clone是非常棘手的在任何情況下都正確地執行,幾乎要被病理
  • 複製對象的重要性將永遠保持,因爲對象字段經常需要防守複製
  • 拷貝構造函數和靜態工廠方法提供替代克隆,並且更容易實現
+1

另外,'clone'的本地實現只會給你一個淺拷貝。 –