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?
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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With