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 fast
the question says shallowcopy not deepcopy.Copying directly reference from one arraylist reference to another will also work right.Deep copy includes copy individual element in arraylist.
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(3);
ArrayList<Integer> list1=list; //shallow copy...
Is there any problem in this ??
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
Instead of iterating manually you can use the copy constructor.
As for the speed difference between that and using clone()
:
Use clone()
, or use the copy-constructor.
The copy-constructor makes additional transformation from the passed collection to array, while the clone()
method uses the internal array directly.
Have in mind that clone()
returns Object
, so you will have to cast to List
.