2015-06-27 31 views
1

表示這是TableDeque類的構造函數(實現了Deque),並且該類中有更多的節點。如何製作一個構造函數來複制包含所有節點信息的原始構造函數?

public TableDeque() { 
    head = new Node<Customer>(null); 
    tail = new Node<Customer>(null); 
    head.join(tail); 
    size = 0; 
    this.setImage("table"); 
} 

我希望做一個複製TableDeque,所以我宣佈另一個構造函數TableDeque作爲參數

public TableDeque (TableDeque copy) { 
    this(); 
    // copy properties from the source TableDeque to the new instance 
} 

因此,TableDeque(this)必須返回重複原來所有的節點信息,但我不知道該怎麼做。

我一直思索和嘗試自己做,但我仍然停留在這個:(請給我解決

回答

0

如果要製作淺拷貝(即更改爲head或者tail對象a壓腳提升體現在兩個地方),只是在copy對象設置字段this一樣 -

public TableDeque (TableDeque copy) 
{ 
    // copy properties from the source TableDeque to the new instance 
    this.head = copy.getHead(); //this function returns the `head` property of TableDeque class 
    this.tail = copy.getTail(); //this function returns the `tail` property of TableDeque class 
    head.join(tail); 
    this.size = copy.getSize(); //this function returns the `size` property of TableDeque class 
    this.setImage(copy.getImage()); //this function returns the `image` property of TableDeque class 

} 

我會說,它始終是建議保持成員變量都在java中私有和公開getter和setter他們。

要創建一個深刻的複印件(headtail變化不會反映), -

public TableDeque (TableDeque copy) 
{ 
    // copy properties from the source TableDeque to the new instance 
    this.head = new Node(copy.getHead()); 
    this.tail = new Node(copy.getTail()); 
    head.join(tail); 
    this.size = copy.getSize(); 
    this.setImage(copy.getImage()); 

} 

然後,你將需要創建Node類的拷貝構造函數也是如此。

2

您Node類創建一個拷貝構造函數,那麼:

public TableDeque (TableDeque copy) { 
    head = new Node(copy.head); 
    tail = new Node(copy.tail); 
    size = copy.size; 
    setImage(copy.image); 
} 

如果存在閉環(使用Set來保持跟蹤節點被訪問),則必須在Node複製構造函數中防止出現無限循環。