array clone() vs Arrays.copyOf()

David Holmes David.Holmes at
Wed Apr 27 10:13:44 UTC 2011

Ulf Zibis said the following on 04/27/11 19:41:
> Am 27.04.2011 11:19, schrieb David Holmes:
>> Ulf Zibis said the following on 04/27/11 19:09:
>>> Am 27.04.2011 02:34, schrieb David Holmes:
>>>> Actually my comments more a response to Remi's assertion that clone 
>>>> should have been used instead, without giving any technical 
>>>> rationale as to why clone would be better, and so much better that 
>>>> it warranted Lance changing the code.
>>>> Personally I think we should be steering people to Arrays.copyOf for 
>>>> all their array copying needs.
>>> Hm, why?
>> One API to learn that covers all the array-copying needs.
> Ok, but from the point of *object-copying* needs, why should one care 
> about sophisticated array stuff?

All I'm saying is that when people think "I need a copy of this array" 
then copyOf is what should come to mind. Why learn two APIs just because 
one may handle a boundary case "better"?

>>>> clone() is effectively legacy code.
>>> What does that mean?
>> Just that it is an old mechanism that has been around for a long time, 
>> is limited to one specific use-case and has been made somewhat 
>> redundant by the newer APIs.
> Ok, you mean Array.copyOf() is clone() XL.
> There are many places, where legacy code became redundant because of 
> some extensions. Should we always avoid them? E.g.:
> - StringBuilder.apend(...) instead '+'
> - Objects.hashcode(obj) instead obj.hashcode()
> - etc...

We should prefer them if they can do an overall better job - else why 
bother adding them. Why teach the old way when there is a more 
advanced/useful new way? Why learn two things when you can learn one 
that covers both use-cases? Sometimes there is a need for both - it 
isn't an absolute.

>>> I prefer clone():
>>> - less to type
>>> - better to read, especially in looong code lines, e.g. as method 
>>> call argument
>> True. Would be nice if defender methods were expanded to allow you to 
>> do anArray.copyOf()
> Can you explain that in other words. Sorry, I'm no english native ;-)

You argued, quite correctly, that anArray.clone() is easier to read in 
some contexts, compared to Arrays.copyOf(anArray, anArray.length). I was 
saying that it is a pity that the defender method mechanism (for adding 
new methods to interfaces -coming in Java 8) wasn't extended so that you 
could also add methods to arrays - if it were then you could write 

Anyway I'm not interested in convincing anybody either way. What I 
objected to originally was the assertion that copyOf should be replaced 
by clone() with no technical justification as to why.


> -Ulf

More information about the core-libs-dev mailing list