How can I clone an ArrayList
and also clone its items in Java?
For example I have:
ArrayList dogs = getDogs();
ArrayList
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
class to implement the Cloneable
interface and override the clone()
method.