c.toArray might (incorrectly) not return Object[] (see 6260652)

David Holmes - Sun Microsystems David.Holmes at Sun.COM
Fri May 22 12:05:30 UTC 2009


Doug Lea said the following on 05/22/09 21:56:
> Sorry; I should have been clearer about why
>   c.toArray(new Object[c.size()])
> is subtly wrong here. ArrayList.size must equal
> the number of elements, which might be different
> than the array size. If c's size shrinks at an
> inconvenient moment during the call, then we might
> think that the trailing null, that toArray(T[] a)
> is required to append if a is too big, is actually a
> (null) element of the collection.

Ah I see.

I'm thinking though that I'd find this hack more aesthetically pleasing:

   static final Object[] ZERO_ARRAY = new Object[0];
   ...
   elementData = c.toArray(ZERO_ARRAY);

this deals with the size issue, gets the right type and only creates one 
array (asuming the collection doesn't concurrently grow).

Cheers,
David





More information about the core-libs-dev mailing list