userimage

How to clone ArrayList and also clone its contents?

 Can I clone an ArrayList and also clone its items in Java 1.5?

For example I have:

ArrayList<Cat> cats= getCats(); 
ArrayList<Cat> clonedList = ....something to do with cats....
And I would expect that objects in clonedList are not the same as in cats list.
userimage

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

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

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

Answer is