7

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

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use the copy constructor whenever you can. clone() is obsolete and should not be used (neither implemented) in new code.

If you extend a class that implements Cloneable, you have little choice but to implement a well-behaved clone method. Otherwise, you are better off providing an alternative means of object copying, or simply not providing the capability. [...] A fine approach to object copying is to provide a copy constructor or copy factory. [...]

Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays.

From Effective Java 2nd Edition, Item 11.

2 Comments

I don't get it. What are all the "problems associated with Cloneable", and why are they so bad that you should never even invoke it?
0

It seems by question that you want to make your collection unmodified so you can use Collections.unmodifiableList().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.