关于Java:如何克隆ArrayList并克隆其内容?

How to clone ArrayList and also clone its contents?

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

例如,我有:

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

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


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

1
2
3
4
5
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()方法。


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

1
2
3
4
5
6
7
8
9
class Dog
{
    public Dog()
    { ... } // Regular constructor

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

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

1
2
3
4
5
6
7
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接口并使用它。这样,您可以编写通用的克隆方法。