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
  • 20,295
  • 14
  • 115
  • 184

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. :-)

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
2

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

array1(int.class, 5);
newacct
  • 119,665
  • 29
  • 163
  • 224
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
  • 19,446
  • 5
  • 33
  • 61