array clone() vs Arrays.copyOf()
Stuart Marks
stuart.marks at oracle.com
Tue Apr 26 15:20:32 UTC 2011
Hi David,
I have a general code style question about this. This arose in the review of
Lance's webrevs for 7038565 [1] but I'm starting a new thread since I don't
want further discussion to drag out that review.
In that review, Lance initially used Arrays.copyOf() to do defensive copying of
an array. Rémi suggested calling clone() instead, and Lance changed it, but it
looks like you (David) convinced him to change it back to use Arrays.copyOf().
(Quotes from the emails are below, but the attribution is hard to follow.)
What's the rationale for using Arrays.copyOf() in this case? To me, clone() is
the clearest and most concise way of making the copy. Arrays.copyOf() is
slightly more verbose and the reader has to do a tiny bit of analysis to
determine that the length isn't being changed, since the value passed is the
current length. Is there some other reason I'm not aware of that
Arrays.copyOf() should be preferred?
I guess, one point is that it's hard to find the javadoc for the array clone()
call. :-)
I guess I'm mainly aiming this at David since he seemed to be the strongest
advocate for the use of Arrays.copyOf(), but I'd welcome opinions from others
as well.
s'marks
[1] http://mail.openjdk.java.net/pipermail/core-libs-dev/2011-April/006694.html
On 4/25/11 9:28 AM, Lance Andersen - Oracle wrote:
> On Apr 23, 2011, at 6:11 AM, David Holmes wrote:
>
>> > Rémi Forax said the following on 04/23/11 04:22:
>>> >> On 04/22/2011 06:51 PM, Lance Andersen - Oracle wrote:
>>>>> >>>>
>>>>> >>>> You should use clone() instead of Arrays.copyOf.
>>>> >>>
>>>> >>> Can you explain why you have a preference for clone() in this case?
>>> >> It does the job :)
>>> >> Arrays.copyOf() allows to resize the array.
>> >
>> > So? That's not a reason to not use Arrays.copyOf. Look at copyOf as the new improved version of clone.
>> >
More information about the core-libs-dev
mailing list