4

I've learned following two methods for creating generic arrays.

One is

@SuppressWarnings("unchecked")
static <T> T[] array1(final Class<T> elementType, final int size) {

    return (T[]) Array.newInstance(elementType, size);
}

And the other is

static <T> T[] array2(final Class<T[]> arrayType, final int size) {

    return arrayType.cast(Array.newInstance(arrayType.getComponentType(), size));
}

Which is better? Are they same (internally)? Is any case actually wrong?

Jin Kwon
  • 17,188
  • 11
  • 87
  • 147

3 Answers3

6

Behind the scenes, the two do effectively the same thing, except that in option 1 you're passing in T's class object and in option 2 you're passing in T[]'s class object.

I prefer option 1 because it's shorter and easier to read. Then again, it's the same as Array.newInstance with a cast added, so I'm not sure that your method adds a lot of value. :-)

Chris Jester-Young
  • 206,112
  • 44
  • 370
  • 418
2

Note that the first one is not type-safe. For example, the following causes a ClassCastException:

array1(int.class, 5);
newacct
  • 110,405
  • 27
  • 152
  • 217
0

Another (better) way to create generic arrays

@SafeVarargs
static <E> E[] newArray(int length, E... array)
{
    return Arrays.copyOf(array, length);
}


Integer[] ints = newArray(10);

String[] strings = newArray(10); 
ZhongYu
  • 18,232
  • 5
  • 28
  • 55