ArrayFactory SAM type / toArray

Joshua Bloch josh at
Wed Sep 19 23:49:16 PDT 2012


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


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