3

My, perhaps naive, solution for cloning an ArrayList (Vector replacement) is

ArrayList<Double> alBis = (ArrayList<Double>) alOriginal.clone(); 

considering that because the array contains immutable Doubles, I don't need to clone them, but only the container.

As clone() returns an Object I put there the cast, but then -Xlint complains it is an unchecked cast.

So, what now? Ignore it with supressWarnings? Create a new ArrayList and copy the orginal elements with a compact for? Any library method similar to Arrays.copyOf()?

I read Unchecked cast warning but the accepted way is incredible complex.

3 Answers 3

14

clone() has major flaws, see this Question for reference. Don't use it!

Instead, all standard Collections have copy constructors. Use them:

List<Double> original = // some list List<Double> copy = new ArrayList<Double>(original); 

Reference:

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

7 Comments

"clone() has major flaws" Can you elaborate? I haven't noticed any in the answers to the linked question.
Read Effective Java by Joshua Bloch
When considering use of a clone versus a copy constructor, one needs to consider what should happen if the passed-in object is of a class derived from the expected class. In the case of clone, the new object will be the same class as the original; in the case of a copy constructor, it will be of the expected class. In some cases, one behavior will be correct and the other decidedly wrong, with different behavior required in different cases.
@supercat nonsense. You can't invoke clone() without knowing what class you are dealing with, because clone() is not backed by any interface (Cloneable is just a marker interface). With thqt same knowledge, you can choose the Copy constructor of the correct class.
and by the same logic (clone is not backed by any interface) using clone() also violates Effective Java Item 52: "Refer to objects by their interfaces"
|
4

Is it wrong to use .clone()?

It should be avoided whenever possible. It is an obsolete, badly designed and fundamentally broken API. Better use the copy constructor as @Sean suggested.

Comments

1

Personally I would recommend Google guava-libraries, and:

 ImmutableCollection<Double> copy = ImmutableList.copyOf(original); 

And do not use JRE clone, because it sucks (if you want to know why, then read references).

Reference:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.