Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

java - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...