2013-05-02 150 views
3

我想創建一個考慮對象是可變的複製構造函數。我的複製構造函數是錯誤的;我似乎無法弄清楚我做錯了什麼。Java複製構造函數ArrayLists

請不要告訴我使用clone()。如何在這種情況下完成複製構造函數?我是Java新手,非常感謝任何幫助。

public class MyList { 


public ArrayList<Cool> people; 

/** 
* "people" variable as a new (empty) ArrayList of Cool objects. 
*/ 
public MyPersonList() 
{ 
    people = new ArrayList<Cool>(0);  
} 


/** 
* A copy constructor which makes the right kind of copy considering 
* a Cool is mutable. 
*/ 
public MyList(MyList other) 
{ 
    people = new ArrayList<Cool>(); 

    for(Cool p:people) 
    { 
     people.add(p); 
    } 

} 

回答

3

簡單:你迭代people但你應該遍歷other.people變量。

剛一說明:ArrayList已經提供了一個構造函數添加另一個集合中的所有項目:

ArrayList(Collection<? extends E> c) 

這樣:

people = new ArrayList<Cool>(other.people); 

就足夠了。

+0

'other.people'。也許增加一個'getPeople()'/'people()'方法返回列表的一個副本。 – 2013-05-02 00:43:49

+0

當我做other.people時,讓它= people = new ArrayList (other.people);這是不正確的 – qkad 2013-05-02 00:49:28

+0

是因爲酷是可變的? – qkad 2013-05-02 00:55:01

8

注意:克隆列表與克隆列表中的元素不同。

這些方法都沒有工作,你希望他們的方式:

//1 
people = new ArrayList<Cool>(other.people); 

//2 
people = new ArrayList<Cool>(); 
for(Cool p : other.people) { 
    people.add(p); 
} 

上面的方法將填補people使得它包含相同的元素other.people

但是,您不希望它包含相同的元素。你想用other.people中的元素克隆來填充它。

最好的辦法是這樣的:

people = new ArrayList<Cool>(other.people.size()); 
for(Cool p : other.people) { 
    people.add((Cool)p.clone()); 
} 

確保Cool工具Cloneable。如有必要,覆蓋clone()

2
public MyList(MyList other) 
{ 
    people = new ArrayList<Cool>(); 

    for(Cool p:people) 
    { 
     people.add(p); 
    } 

} 

將其更改爲:

public MyList(MyList other) 
{ 
    people = new ArrayList<Cool>(); 

    for(Cool p : other.people) 
    { 
     people.add(p); 
    } 

}