2012-01-18 129 views
0

可能重複:
How to clone ArrayList and also clone its contents?克隆列表

我有一個ArrayList<Widget>,我想「深」的克隆,以便在原始列表進行修改的任何項目做對克隆列表中的項目沒有任何影響:

ArrayList<Widget> origList = getMyList(); 
ArrayList<Widget> cloneList = origList.clone(); 

// Remove the 5th Widget from the origina list 
origList.remove(4); 

// However, the cloneList still has the 5th Widget and is unchanged 

// Change the id of the first widget 
origList.get(0).setId(20); 

// However in cloneList, the 1st Widget's ID is not 20 

什麼是b最安全的方式來完成這個?我想,這不是那麼簡單:

ArrayList<Widget> cloneList = origList.clone(); 

我想象中的事實,這是一個內置的ArrayList型,加上一個事實,即它的通用性,將會使事情變得複雜。我也想象我需要爲我的Widget類寫一個特殊的clone()覆蓋?

在此先感謝!

編輯
我還完全接受,如果有一個公共JAR在那裏,確實對我來說這繁重,所以請隨時提出建議,但我仍想知道如何做這個時尚的方式,讓我可以學習;-)

+0

請在發佈問題前進行搜索 – jere 2012-01-18 18:26:25

回答

2

一些權威人士不鼓勵使用cloneHere is one link off google。這並不是說不要這樣做,而只是意識到自己進入了什麼,並且一定要測試(好吧,一直這樣做)。

我可能會把一個deepCopy方法放在根類上,並且只是用拷貝構造函數來拷貝蠻力的方法。複製構造函數是一個構造函數,它接受有關類的實例,並創建一個新實例,將參數的內部狀態複製到新實例中。

4

你需要迭代原始列表中的每個項目,並單獨克隆每個項目,然後添加他們到一個新的'克隆'項目清單。

喜歡的東西:

List<Widget> origList = getMyList(); 
List<Widget> clonedList = clone(origList); 

private List<Widget> clone(List<Widget> listToClone) { 
    List<Widget> clonedList = new LinkedList<Widget>(); 

    for (Widget widget : listToClone) { 
    clonedList.add(widget.clone()); 
    } 

    return clonedList; 
} 

對於這個工作,你必須有你的Widget對象實現Cloneable接口,clone()方法。沒有其他需要。

但是,正如其他海報所說,很多人會認爲在Java中執行clone並不是很好的依靠,最好避免。