我如何克隆一个数组列表,也克隆其项目在Java?

例如,我有:

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

我希望clonedList中的对象与dogs list中的对象不一样。


当前回答

我想我找到了一个非常简单的方法来创建一个深度复制数组列表。假设你想复制一个字符串数组列表arrayA。

ArrayList<String>arrayB = new ArrayList<String>();
arrayB.addAll(arrayA);

如果对你不起作用请告诉我。

其他回答

List<Dog> dogs;
List<Dog> copiedDogs = dogs.stream().map(dog -> SerializationUtils.clone(dog)).Collectors.toList());

这将深度复制每个狗

您需要手动克隆数组列表(通过迭代数组列表并将每个元素复制到一个新的数组列表中),因为clone()不会为您做这件事。原因是ArrayList中包含的对象本身可能无法实现Clonable。

编辑:…而这正是Varkhan的代码所做的。

对于你的对象重写clone()方法

class You_class {

    int a;

    @Override
    public You_class clone() {
        You_class you_class = new You_class();
        you_class.a = this.a;
        return you_class;
    }
}

调用.clone() for Vector obj或ArraiList obj....

我想我找到了一个非常简单的方法来创建一个深度复制数组列表。假设你想复制一个字符串数组列表arrayA。

ArrayList<String>arrayB = new ArrayList<String>();
arrayB.addAll(arrayA);

如果对你不起作用请告诉我。

简单的方法,使用common -lang-2.3.jar的java库克隆列表

链接下载commons-lang-2.3.jar

如何使用

oldList.........
List<YourObject> newList = new ArrayList<YourObject>();
foreach(YourObject obj : oldList){
   newList.add((YourObject)SerializationUtils.clone(obj));
}

我希望这篇文章能有所帮助。

:D