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. :-)
Note that the first one is not type-safe. For example, the following causes a ClassCastException:
array1(int.class, 5);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.