小编典典

Java-如何克隆ArrayList并同时克隆其内容?

java

如何克隆ArrayList Java并同时在Java中克隆其项目?

例如,我有:

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ....something to do with dogs....

我希望其中的对象clonedList与狗列表中的对象不同。


阅读 966

收藏
2020-02-25

共2个答案

小编典典

你将需要迭代这些项目,然后逐个克隆它们,然后将克隆放入结果数组中。

public static List<Dog> cloneList(List<Dog> list) {
    List<Dog> clone = new ArrayList<Dog>(list.size());
    for (Dog item : list) clone.add(item.clone());
    return clone;
}

显然,要使该方法起作用,你将必须使你的Dog类实现Cloneable接口并重写该clone()方法。

2020-02-25
小编典典

我个人将为Dog添加一个构造函数:

class Dog
{
    public Dog()
    { ... } // Regular constructor

    public Dog(Dog dog) {
        // Copy all the fields of Dog.
    }
}

然后进行迭代(如Varkhan的答案所示):

public static List<Dog> cloneList(List<Dog> dogList) {
    List<Dog> clonedList = new ArrayList<Dog>(dogList.size());
    for (Dog dog : dogList) {
        clonedList.add(new Dog(dog));
    }
    return clonedList;
}

我发现这样做的好处是你无需费心处理Java中破碎的可克隆内容。它还与你复制Java集合的方式匹配。

另一种选择是编写自己的ICloneable接口并使用它。这样,你可以编写通用的克隆方法。

2020-02-25