ArrayFactory SAM type / toArray

David M. Lloyd david.lloyd at redhat.com
Wed Sep 19 14:09:24 PDT 2012


On 09/19/2012 03: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.

Seems like you could as well just pass a Class<? super T> and not have 
all these lambdas around (iirc reflective array creation is a hotspot 
intrinsic so perf shouldn't be an issue).
-- 
- DML




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