How can I clone an ArrayList
and also clone its items in Java?
For example I have:
ArrayList dogs = getDogs();
ArrayList
The below worked for me..
in 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 createCopy(List dogs) {
List newDogsList= new ArrayList<>();
if (CollectionUtils.isNotEmpty(dogs)) {
dogs.stream().forEach(dog-> newDogsList.add((Dog) SerializationUtils.clone(dog)));
}
return newDogsList;
}
Here the new list which got created from createCopy method is created through SerializationUtils.clone(). So any change made to new list will not affect original list