ArrayFactory SAM type / toArray

Raab, Donald Donald.Raab at gs.com
Wed Sep 19 19:27:51 PDT 2012


I like David's approach of passing Class to toArray().  I also didn't mind the approach of passing a factory interface where you could use a lambda.

Then when I saw the example code below with a new Integer[0] array in a static variable, I remembered how many times I've written this kind of code over the years with static empty arrays and started thinking.

Could we add the following methods to the Class class?

T[] emptyArray()
T[] newArray(int size)

I may be missing something simple in Java's static type system somewhere that makes this not possible, but imagine if we could write the following:

Integer.class.emptyArray() 

or 

Integer.class.newArray(0) 

and they returned the same static instance (held in the class of course), which would be possible because the empty array is immutable.  This would be an improvement even with the current T[] toArray(T[]) cases because we could forever get rid of spurious empty array creation.

Someone please wake me up if this is just an unfortunate pipe dream.


From: lambda-libs-spec-experts-bounces at openjdk.java.net [mailto:lambda-libs-spec-experts-bounces at openjdk.java.net] On Behalf Of Joshua Bloch
Sent: Wednesday, September 19, 2012 8:12 PM
To: David M. Lloyd
Cc: lambda-libs-spec-experts at openjdk.java.net
Subject: Re: ArrayFactory SAM type / toArray

David,

On Wed, Sep 19, 2012 at 4:45 PM, David M. Lloyd <david.lloyd at redhat.com> wrote:

It should be:

  <S super T> S[] toArray(Class<S> clazz);

Actually we considered and rejected that parameterization  back in '03 (if memory serves).  Sometimes the client knows more about the contents of the array than the compiler does.  So, for example, suppose you know that a Collection<Number> contains only Integers.  Then you might write:

    private static final Integer[] EMPTY_INTEGER_ARRAY = new Integer[0];
    ...

    Collection<Number> c = ... ;

    ...

    Integer[] a = c.toArray(EMPTY_INTEGER_ARRAY);

The type system can't prove that the call won't result in an ArrayStoreException, but you (the programmer) know that it won't.  Perhaps we made the wrong decision, but it was a conscious decision.

     Josh



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