Stream.toArray()

Remi Forax forax at univ-mlv.fr
Wed Dec 5 08:43:38 PST 2012


On 12/05/2012 04:44 PM, David M. Lloyd wrote:
> Agreed on the array class - another reason is that otherwise folks 
> might expect this to work:
>
> int[] foo = stream.toArray(int[].class);

and they will never expect this to work ?
     int[] foo = stream.toArray(int.class);

I've used an array class because this is what you want an instance of an 
array class,
so I've tried:
     public <A extends Object[]> A asArray(Class<A> clazz);
to reject toArray(int[])  but for a reason that I don't understand you 
can not use Object[] as bound.

Rémi

>
> On 12/05/2012 09:39 AM, Brian Goetz wrote:
>> Agree on the general form -- toArray(clazz) is definitely better than
>> the current bad alternatives offered by Collection.
>>
>> I prefer that the argument be the component class, not the array class.
>>   I think toArray(Foo.class) is far more natural to users than
>> toArray(Foo[].class).
>>
>> On 12/5/2012 10:33 AM, Remi Forax wrote:
>>> Restarting a thread that ends without clear winner.
>>>
>>> Currently, Stream.toArray() is specified as:
>>>    Object[] toArray()
>>>
>>> which is not what users want, given the lack of reified generics and 
>>> the
>>> fact that it's usually hard for a user to predict the number of 
>>> elements
>>> of a Stream,
>>> the best signature seems to be:
>>>    <A> A[] toArray(Class<A> arrayClass)
>>> with arrayClass.isArray() returning true and
>>> arrayClass.getComponentType().isPrimitive() returning false
>>> (or if you prefer Object[].class.isAssignableFrom(arrayClass) returning
>>> true)
>>>
>>> example of usage,
>>>    Person[] coolPersons =
>>> persons.stream().filter(person#isCool()).toArray(Person[].class);
>>>
>>> cheers,
>>> Rémi
>>>
>
>



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