我如何克隆一个数组列表,也克隆其项目在Java?
例如,我有:
ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ....something to do with dogs....
我希望clonedList中的对象与dogs list中的对象不一样。
我如何克隆一个数组列表,也克隆其项目在Java?
例如,我有:
ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ....something to do with dogs....
我希望clonedList中的对象与dogs list中的对象不一样。
当前回答
下面是一个使用泛型模板类型的解决方案:
public static <T> List<T> copyList(List<T> source) {
List<T> dest = new ArrayList<T>();
for (T item : source) { dest.add(item); }
return dest;
}
其他回答
我想我找到了一个非常简单的方法来创建一个深度复制数组列表。假设你想复制一个字符串数组列表arrayA。
ArrayList<String>arrayB = new ArrayList<String>();
arrayB.addAll(arrayA);
如果对你不起作用请告诉我。
您将需要迭代这些项,并逐个克隆它们,将克隆放入结果数组中。
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()方法。
下面是一个使用泛型模板类型的解决方案:
public static <T> List<T> copyList(List<T> source) {
List<T> dest = new ArrayList<T>();
for (T item : source) { dest.add(item); }
return dest;
}
简单的方法是
ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>(dogs);
我认为目前的绿色答案很糟糕,为什么你会问?
它可能需要添加大量代码 它要求你列出所有要复制的列表并这样做
序列化的方式在我看来也是不好的,你可能不得不到处添加Serializable。
那么解决方案是什么呢?
Java深度克隆库 克隆库是一个小型的开源(apache许可)java库,它对对象进行深度克隆。对象不必实现克隆接口。实际上,这个库可以克隆任何java对象。它可以用在缓存实现中,如果你不想修改缓存对象,或者当你想创建对象的深度副本时。
Cloner cloner=new Cloner();
XX clone = cloner.deepClone(someObjectOfTypeXX);
请登录https://github.com/kostaskougios/cloning查看