How can I clone an ArrayList
and also clone its items in Java?
For example I have:
ArrayList dogs = getDogs();
ArrayList
I, personally, would add a constructor to Dog:
class Dog
{
public Dog()
{ ... } // Regular constructor
public Dog(Dog dog) {
// Copy all the fields of Dog.
}
}
Then just iterate (as shown in Varkhan's answer):
public static List cloneList(List dogList) {
List clonedList = new ArrayList(dogList.size());
for (Dog dog : dogList) {
clonedList.add(new Dog(dog));
}
return clonedList;
}
I find the advantage of this is you don't need to screw around with the broken Cloneable stuff in Java. It also matches the way that you copy Java collections.
Another option could be to write your own ICloneable interface and use that. That way you could write a generic method for cloning.