How can I clone an ArrayList
and also clone its items in Java?
For example I have:
ArrayList dogs = getDogs();
ArrayList
All standard collections have copy constructors. Use them.
List original = // some list
List copy = new ArrayList(original); //This does a shallow copy
clone()
was designed with several mistakes (see this question), so it's best to avoid it.
From Effective Java 2nd Edition, Item 11: Override clone judiciously
Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.
This book also describes the many advantages copy constructors have over Cloneable/clone.
Consider another benefit of using copy constructors: Suppose you have a HashSet s
, and you want to copy it as a TreeSet
. The clone method can’t offer this functionality, but it’s easy with a conversion constructor: new TreeSet(s)
.