I need to write out a method to clone a nested ArrayList
.
The nested ArrayList
looks like this:
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.
How should I go about cloning the elements of the nested ArrayList<Ship>
?
However, this doesn't clone the elements of the nested ArrayList and instead just copies over a reference to it.
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.
You could define a copy constructor in Ship
for example :
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:
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)));
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.