2013-05-02 51 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); 
    } 

}