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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…