ArrayFactory SAM type / toArray

Remi Forax forax at
Thu Sep 20 01:13:27 PDT 2012

On 09/20/2012 08:49 AM, Joshua Bloch wrote:
> Donald,
> I believe this does work, with one caveat: if the type is generic, 
> these methods will return a generic array, which will generate an 
> unchecked cast warning.

No, with the current JLS rules, you can't create a Class of T with a 
generic T without a warning.
List<String>.class doesn't compile and foo = new ArrayList<String>(), 
foo.getClass() returns a Class<ArrayList>
(and not a Class>ArrayList<T>>), so you can't create a generic array 
without having an unsafe cast somewhere.

But there is an issue with Class that represents a primitive type,
int.class is typed Class<Integer>, so either emptyArray() should return 
an Integer[] or
it should throw an exception.

>     Josh


> On Wed, Sep 19, 2012 at 7:27 PM, Raab, Donald <Donald.Raab at 
> <mailto:Donald.Raab at>> wrote:
>     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.

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