Weird compile-time behavior when trying to use primitive type in generics
Posted
by polygenelubricants
on Stack Overflow
See other posts from Stack Overflow
or by polygenelubricants
Published on 2010-03-16T10:00:05Z
Indexed on
2010/03/16
10:56 UTC
Read the original article
Hit count: 234
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?
© Stack Overflow or respective owner