Tuesday, November 22, 2011


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

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.

Thanks for any answer!






Answers



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 object to implement the Cloneable interface, and the clone() method.

No comments:

Post a Comment