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

例如,我有:

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

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


当前回答

下面的方法对我有用。

在Dog.java

public Class Dog{

private String a,b;

public Dog(){} //no args constructor

public Dog(Dog d){ // copy constructor
   this.a=d.a;
   this.b=d.b;
}

}

 -------------------------

 private List<Dog> createCopy(List<Dog> dogs) {
 List<Dog> newDogsList= new ArrayList<>();
 if (CollectionUtils.isNotEmpty(dogs)) {
 dogs.stream().forEach(dog-> newDogsList.add((Dog) SerializationUtils.clone(dog)));
 }
 return newDogsList;
 }

在这里,由createCopy方法创建的新列表是通过SerializationUtils.clone()创建的。 因此,对新列表所做的任何更改都不会影响原始列表

其他回答

所有标准集合都有复制构造函数。使用它们。

List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original); //This does a shallow copy

Clone()的设计有几个错误(请参阅这个问题),所以最好避免使用它。

来自Effective Java第二版,第11项:明智地覆盖克隆

Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

这本书还描述了复制构造函数相对于克隆/克隆的许多优点。

他们不依赖于有风险的语言外对象创造 机制 他们不要求严格遵守文件记录不全的约定 它们与final字段的正确使用并不冲突 它们不会抛出不必要的受控异常 它们不需要类型转换。

考虑使用复制构造函数的另一个好处:假设您有一个HashSet,并且希望将其复制为TreeSet。克隆方法不能提供这种功能,但是使用转换构造函数new TreeSet(s)就很容易实现。

简单的方法,使用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

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

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的代码所做的。

我刚刚开发了一个库,能够克隆一个实体对象和java.util.List对象。只需从https://drive.google.com/open?id=0B69Sui5ah93EUTloSktFUkctN0U下载jar,并使用静态方法cloneListObject(List List)。该方法不仅克隆List,而且克隆所有实体元素。