qka*_*kad 3 java constructor copy
我正在尝试创建一个复制构造函数,考虑到对象是可变的.我的拷贝构造函数错了; 我似乎无法弄清楚我做错了什么.
请不要告诉我使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:克隆列表与克隆列表中的元素不同.
这些方法都不像您希望的那样工作:
//1
people = new ArrayList<Cool>(other.people);
//2
people = new ArrayList<Cool>();
for(Cool p : other.people) {
people.add(p);
}
Run Code Online (Sandbox Code Playgroud)
上面的方法将填充people,使其包含与...相同的元素other.people.
但是,您不希望它包含相同的元素.你想用它中的元素克隆来填充它other.people.
最好的方法是这样的:
people = new ArrayList<Cool>(other.people.size());
for(Cool p : other.people) {
people.add((Cool)p.clone());
}
Run Code Online (Sandbox Code Playgroud)
确保Cool工具Cloneable.clone()必要时覆盖.
简单地说:您正在迭代,people但您应该迭代other.people变量。
请注意:ArrayList已经提供了一个构造函数来添加另一个集合的所有项目:
ArrayList(Collection<? extends E> c)
Run Code Online (Sandbox Code Playgroud)
所以:
people = new ArrayList<Cool>(other.people);
Run Code Online (Sandbox Code Playgroud)
足够。