Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a copy of ArrayList object which is type of List?

Tags:

java

clone

copy

I studied that Java passes object references by value, and in order to make a local copy of an object I can either do clone() or copy-constructor. I also looked at deep/shallow copy as well as several posts on Stack Overflow.

I am looking at this example:

List<String> list = new ArrayList<String>();
String one = "one"
list.add(one);

Only a few articles I read mention that ArrayList implements cloneable, but does not really say how to make a local copy of "list" if the type is List, not ArrayList which does not implement cloneable.

I can call clone() if "list" is type of ArrayList.

ArrayList<String> list = new ArrayList<String>();
list.clone();

But if type is List, I cannot.

Should I just use the copy constructor like below to make a local copy? What is the best way to make a copy of "list"?

List<String> tmpList = new ArrayList<String>(list);
like image 886
Meow Avatar asked Aug 04 '10 21:08

Meow


1 Answers

Passing the list into the constructor is probably the best way to go. The constructor invocation itself will use, behind the scenes, System.arraycopy. So it will effectively detach the local copy from the list passed in through the constructor.

like image 52
John Vint Avatar answered Oct 02 '22 21:10

John Vint