I need a shallow copy of an java ArrayList
, should I use clone()
or iterate over original list and copy elements in to new arrayList, which is faster ?
ArrayList clone() method is used to create a shallow copy of the list. In the new list, only object references are copied. If we change the object state inside the first ArrayList, then the changed object state will be reflected in the cloned ArrayList as well.
ArrayList cloned = new ArrayList(collection c); where c is the collection containing elements to be added to this list. Approach: Create a list to be cloned. Clone the list by passing the original list as the parameter of the copy constructor of ArrayList.
clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.
The iterator can be used to iterate through the ArrayList wherein the iterator is the implementation of the Iterator interface. Some of the important methods declared by the Iterator interface are hasNext() and next().
No need to iterate:
List original = ... List shallowCopy = new ArrayList(original);
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With