我想創建一個考慮對象是可變的複製構造函數。我的複製構造函數是錯誤的;我似乎無法弄清楚我做錯了什麼。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);
}
}
'other.people'。也許增加一個'getPeople()'/'people()'方法返回列表的一個副本。 – 2013-05-02 00:43:49
當我做other.people時,讓它= people = new ArrayList(other.people);這是不正確的 –
qkad
2013-05-02 00:49:28
是因爲酷是可變的? – qkad 2013-05-02 00:55:01