Java 复制构造函数 ArrayLists

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16328602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:39:30  来源:igfitidea点击:

Java Copy Constructor ArrayLists

javaconstructorcopy

提问by qkad

I am trying to create a copy constructor considering the object is mutable. My copy constructor is wrong; I can't seem to figure out what I am doing wrong.

考虑到对象是可变的,我正在尝试创建一个复制构造函数。我的复制构造函数是错误的;我似乎无法弄清楚我做错了什么。

Please do NOT tell me to use clone(). How would I complete the copy constructor in this situation? I am new to Java and would really appreciate any help.

请不要告诉我使用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);
    }

}

回答by Lone nebula

Note: Cloning the lists, isn't the same as cloning the elements in the list.

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

None of these approaches work the way you want them to:

这些方法都没有按照您希望的方式工作:

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

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

The approaches above will fill peoplesuch that it contains the same elements as other.people.

上面的方法将填充people,使其包含与other.people.

However, you don't want it to contain the same elements. You want to fill it with clones of the elements in other.people.

但是,您不希望它包含相同的元素。你想用other.people.

The best approach would be something like this:

最好的方法是这样的:

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

Make sure Coolimplements Cloneable. Override clone()if necessary.

确保Cool实现Cloneable. clone()必要时覆盖。

回答by Hyman

Simply: you are iterating over peoplebut you should iterate over other.peoplevariable.

简单地说:您正在迭代,people但您应该迭代other.people变量。

Just a note: ArrayListalready provides a constructor to add all items of another collection:

请注意:ArrayList已经提供了一个构造函数来添加另一个集合的所有项目:

ArrayList(Collection<? extends E> c)  

so:

所以:

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

is enough.

足够。

回答by xiriusly

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

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

}

change it to :

将其更改为:

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

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

}