Collection.toArray <was> Re: Loose ends inventory

Brian Goetz brian.goetz at oracle.com
Tue Jun 11 09:02:41 PDT 2013


Much of this was covered in the thread "ArrayFactory SAM" from September 
2012.  Salient points:

  - The existing toArray methods on Collection both suck.  (Yes, they 
are the best we could do in the 1.2 days.)
    -- The no-arg always allocates and returns an Object[] array instead 
of the right type, which is usually not what the user wants
    -- The "pass an array" version gives you the right type but is 
inherently racy and requires use of reflection
  - This pick-your-poison choice reflects a fundamental "shared 
information" problem; the client knows best how to create the array, but 
the collection implementation knows best what size to use.  Passing a 
lambda (we actually have array constructor method refs for this: 
Foo[]::new) perfectly encapsulates the client-specific information, 
leaving the library in control of the remaining details (how big to 
allocate, whether to reallocate, etc.)

Lambdas enable something that is better from a type safety, performance, 
and code clarity perspective.  We did much better with Stream.toArray 
than Collection could have in 1997.  Now people are asking to retrofit 
that goodness to Collection too, and make Collection.toArray consistent 
with Stream.toArray.  This makes perfect sense to me.



On 6/11/2013 11:45 AM, Doug Lea wrote:
> On 06/11/13 11:30, Paul Sandoz wrote:
>> On Jun 11, 2013, at 1:21 AM, Brian Goetz <brian.goetz at Oracle.COM> wrote:
>>>> - Add A[] toArray(IntFunction<A[]> generator) to Collection.
>>>
>>> Got stalled.
>>>
>>
>> This got stalled on the niggle of toArray(null) which would be
>> ambiguous, and likely affects tests in the TCK.
>>
>
> Why not just given another name?
>
> Also, can someone remind me of the use cases? Seems a little marginal.
>
> -Doug
>
>


More information about the lambda-libs-spec-experts mailing list