How can I clone an ArrayList
and also clone its items in Java?
For example I have:
ArrayList dogs = getDogs();
ArrayList
Basically there are three ways without iterating manually,
1 Using constructor
ArrayList dogs = getDogs();
ArrayList clonedList = new ArrayList(dogs);
2 Using addAll(Collection extends E> c)
ArrayList dogs = getDogs();
ArrayList clonedList = new ArrayList();
clonedList.addAll(dogs);
3 Using addAll(int index, Collection extends E> c)
method with int
parameter
ArrayList dogs = getDogs();
ArrayList clonedList = new ArrayList();
clonedList.addAll(0, dogs);
NB : The behavior of these operations will be undefined if the specified collection is modified while the operation is in progress.