import java.lang.reflect.Array;
public class PrimitiveArrayGeneric {
static <T> T[] genericArrayNewInstance(Class<T> componentType) {
return (T[]) Array.newInstance(componentType, 0);
}
public static void main(String args[]) {
int[] intArray;
Integer[] integerArray;
intArray = (int[]) Array.newInstance(int.class, 0);
// Okay!
integerArray = genericArrayNewInstance(Integer.class);
// Okay!
intArray = genericArrayNewInstance(int.class);
// Compile time error:
// cannot convert from Integer[] to int[]
integerArray = genericArrayNewInstance(int.class);
// Run time error:
// ClassCastException: [I cannot be cast to [Ljava.lang.Object;
}
}
I'm trying to fully understand how generics works in Java. Things get a bit weird for me in the 3rd assignment in the above snippet: the compiler is complaining that Integer[]
cannot be converted to int[]
. The statement is 100% true, of course, but I'm wondering WHY the compiler is making this complaint.
If you comment that line, and follow the compiler's "suggestion" as in the 4th assignment, the compiler is actually satisfied!!! NOW the code compiles just fine! Which is crazy, of course, since like the run time behavior suggests, int[]
cannot be converted to Object[]
(which is what T[]
is type-erased into at run time).
So my question is: why is the compiler "suggesting" that I assign to Integer[]
instead for the 3rd assignment? How does the compiler reason to arrive to that (erroneous!) conclusion?
There is a lot of confusion in the two answers so far, so I created another baffling example to illustrate the underlying issue here:
public class PrimitiveClassGeneric {
static <T extends Number> T test(Class<T> c) {
System.out.println(c.getName() + " extends " + c.getSuperclass());
return (T) null;
}
public static void main(String args[]) {
test(Integer.class);
// "java.lang.Integer extends class java.lang.Number"
test(int.class);
// "int extends null"
}
}
Am I the only one that thinks it's absolutely crazy that the compiler lets the above code compiles?
It wouldn't be unreasonable to print c.getSuperclass().getName()
in the above code, for example, since I specified that T extends Number
. Of course now getName()
will throw NullPointerException
when c == int.class
, since c.getSuperclass() == null
.
And to me, that's a very good reason to reject the code from compiling in the first place.
Perhaps the ultimate craziness:
int.class.cast(null);
That code compiles AND runs fine.