Skip to content
Advertisement

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

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);

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement