How to clone ArrayList and also clone its contents?

palig picture palig · Apr 3, 2009 · Viewed 432.3k times · Source

How can I clone an ArrayList and also clone its items in Java?

For example I have:

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ....something to do with dogs....

And I would expect that objects in clonedList are not the same as in dogs list.

Answer

Varkhan picture Varkhan · Apr 3, 2009

You will need to iterate on the items, and clone them one by one, putting the clones in your result array as you go.

public static List<Dog> cloneList(List<Dog> list) {
    List<Dog> clone = new ArrayList<Dog>(list.size());
    for (Dog item : list) clone.add(item.clone());
    return clone;
}

For that to work, obviously, you will have to get your Dog class to implement the Cloneable interface and override the clone() method.