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

例如,我有:

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

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


当前回答

基本上有三种不需要手动迭代的方法,

1使用构造函数

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>(dogs);

2使用addAll(Collection<?c)扩展;

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(dogs);

3使用addAll(int index, Collection<?用int形参扩展E> c)方法

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(0, dogs);

注意:如果指定的集合在操作进行时被修改,这些操作的行为将是未定义的。

其他回答

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

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()方法。

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

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

基本上有三种不需要手动迭代的方法,

1使用构造函数

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>(dogs);

2使用addAll(Collection<?c)扩展;

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(dogs);

3使用addAll(int index, Collection<?用int形参扩展E> c)方法

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(0, dogs);

注意:如果指定的集合在操作进行时被修改,这些操作的行为将是未定义的。

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

这将深度复制每个狗

对于你的对象重写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....