ArrayFactory SAM type / toArray

Remi Forax forax at univ-mlv.fr
Wed Sep 19 13:54:07 PDT 2012


On 09/19/2012 10:39 PM, Brian Goetz wrote:
> In looking at the Collection API, there are two forms of toArray 
> method, both of which are unfortunate:
>
>   Object[] toArray() -- returns an Object[], not a T[]
>
>   T[] toArray(T[]) -- reflective instantiation
>
> Lambdas offer us a way out of this:
>
> interface ArrayFactory<T> {
>     T[] make(int n);
> }
>
> interface Collection<T> {
>     T[] toArray(ArrayFactory<T> factory) default {
>         return toArray(factory.make(size());
>     }
> }
>
> The default is imperfect (though no worse than what clients typically 
> do), and concrete implementations of Collection can do better.
>
> Given that Stream has a toArray method, my preference would be to expose
>
>   T[] toArray(ArrayFactory<T>)
>
> possibly as the only toArray method.
>
> We might be able to extend the constructor reference syntax to arrays: 
> Foo[]::new.  If not, n -> new Foo[n] works fine.
>

Why passing a lambda that will be called in the body of the toArray ?
It's simpler to directly pass the array.

Rémi









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