Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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():

  1. It doesn't matter
  2. Most likely there is none
  3. Do a benchmark for your specific system configuration and use case

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 ??

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top