这是来自创建通用数组的两种方法的以下问题。
使用给定的两种方法,
@SuppressWarnings("unchecked")
static <T> T[] array1(final Class<T> elementType, final int size) {
return (T[]) Array.newInstance(elementType, size);
}
static <T> T[] array2(final Class<T[]> arrayType, final int size) {
return arrayType.cast(Array.newInstance(arrayType.getComponentType(), size));
}
这两种方法都适用于 Object 类型。
final Integer[] objectArray1 = array1(Integer.class, 0);
final Integer[] objectArray2 = array2(Integer[].class, 0);
当涉及到原语时,两个调用都不会编译。
// array1
final int[] primitiveArray1 = array1(int.class, 0);
GenericArray.java:12: error: incompatible types
final int[] primitiveArray1 = array1(int.class, 0);
^
required: int[]
found: Integer[]
1 error
// array2
final int[] primitiveArray2 = array2(int[].class, 0);
GenericArray.java:13: error: method array2 in class GenericArray cannot be applied to given types;
final int[] primitiveArray2 = array2(int[].class, 0);
^
required: Class<T[]>,int
found: Class<int[]>,int
reason: inferred type does not conform to declared bound(s)
inferred: int
bound(s): Object
where T is a type-variable:
T extends Object declared in method <T>array2(Class<T[]>,int)
1 error
我该如何处理原始类型?