How to make a deep copy of Java ArrayList [duplicate]
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Person p : oldList) {
newList.add(p.clone());
}
Assuming clone
is correctly overriden inPerson
.
public class Person{
String s;
Date d;
...
public Person clone(){
Person p = new Person();
p.s = this.s.clone();
p.d = this.d.clone();
...
return p;
}
}
In your executing code:
ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
clone.add(p.clone());