[英]How should I go about cloning a nest ArrayList?
I need to write out a method to clone a nested ArrayList
. 我需要写出一种方法来克隆嵌套的ArrayList
。
The nested ArrayList
looks like this: 嵌套的ArrayList
如下所示:
ArrayList<ArrayList<Ship>> theSea = new ArrayList<ArrayList<Ship>>();
I want to copy it to a clone: 我想将其复制到克隆中:
ArrayList<ArrayList<Ship>> seaClone = new ArrayList<ArrayList<Ship>>();
I've tried iterating it and copying over the lists: 我试着迭代它并复制列表:
for(int i = 0; i < theSea.size(); i++){
seaClone.add(theSea.get(i));
}
However, this doesn't clone the elements of the nested ArrayList<Ship>
and instead just copies over a reference to it. 但是,这不会克隆嵌套的ArrayList<Ship>
的元素,而是仅复制对其的引用。
How should I go about cloning the elements of the nested ArrayList<Ship>
? 我应该如何克隆嵌套ArrayList<Ship>
的元素?
However, this doesn't clone the elements of the nested ArrayList and instead just copies over a reference to it. 但是,这不会克隆嵌套ArrayList的元素,而是仅复制对其的引用。
Because it is actually what you are doing : you add the reference of the existing objects in the new List. 因为这实际上是您在做什么:您可以在新列表中添加现有对象的引用。
So instead of, create a new nested ArrayList for each cloned sublist and create new Ship objects as you add elements in the new List
s. 因此,与其替代,为每个克隆的子列表创建一个新的嵌套ArrayList,然后在新List
添加元素时创建新的Ship对象。
You could define a copy constructor in Ship
for example : 您可以在Ship
定义一个复制构造函数,例如:
public Ship(Ship model){
foo = model.foo;
bar = model.bar;
}
You can so write : 您可以这样写:
for(List<Ship> list : theSea){
List<Ship> currentList = new ArrayList<>();
for(Ship ship : list){
currentList.add(new Ship(ship));
}
clone.add(currentList);
}
Assuming Ship
objects are cloneable: 假设Ship
对象是可克隆的:
List<List<Ship>> clone = theSea.stream()
.map(l -> l.stream().map(s -> (Ship)s.clone()).collect(toList()))
.collect(toList());
Something like: 就像是:
ArrayList<ArrayList<Ship>> listCopy = new ArrayList<>();
for (int i=0; i<list.size(); i++) {
ArrayList<Ship> newList = new ArrayList<>();
for (int j=0; j<list.get(i).size(); j++) {
newList.add(new Ship(list.get(i).get(j)));
}
listCopy.add(newList);
}
Observe this line: newList.add(new Ship(list.get(i).get(j)));
观察以下行: newList.add(new Ship(list.get(i).get(j)));
Where you need to pass the object to the constructor and from there duplicate all the attributes, otherwise you will just create a reference to the same class. 您需要将对象传递给构造函数,然后从那里复制所有属性,否则,您将只创建对同一类的引用。
If your ship class is to complex with many other objects inside this task may be difficult and you can use a tool like serializing to json and then revert back to object or using a java deep object cloner. 如果您的飞船类要与许多其他对象一起复杂化,则此任务可能很困难,您可以使用诸如序列化为json然后再恢复为对象或使用Java深对象克隆器之类的工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.