How to clone ArrayList and also clone its contents?

How can I clone ArrayList but also clone its items in Java 1.5?

For example I have:

ArrayList dogs = getDogs();
ArrayList clonedList = …something to do with dogs…
And I would expect that objects in clonedList are not the same as in dogs list.

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 cloneList(List list) {

    List clone = new ArrayList(list.size());

    for(Dog item: list) clone.add(item.clone());

    return clone;

}

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