Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two methods for creating generic arrays

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?

like image 622
Jin Kwon Avatar asked Feb 17 '23 04:02

Jin Kwon


1 Answers

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

like image 123
Chris Jester-Young Avatar answered Feb 26 '23 15:02

Chris Jester-Young