How to clone ArrayList and also clone its contents?

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<Dog> cloneList(List<Dog> dogList) {
    List<Dog> clonedList = new ArrayList<Dog>(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.

Leave a Comment