Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList shallow copy iterate or clone()

Tags:

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 ?

like image 231
tech20nn Avatar asked Apr 07 '10 13:04

tech20nn


People also ask

How do you shallow copy an ArrayList?

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.

How do you copy or clone an ArrayList?

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.

Is clone a shallow copy?

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.

Can you iterate an ArrayList?

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


1 Answers

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

like image 144
Bart Kiers Avatar answered Nov 05 '22 22:11

Bart Kiers