I'm studying generics in this period and today I've found this mystery for me.
Let's consider the following dummy class:
public class Main{
public static void main(String[] args) {
Container<Integer> c = new Container<Integer>();
c.getArray(); //No Exception
//c.getArray().getClass(); //Exception
//int a = c.getArray().length; //Exception
}
}
class Container<T> {
T[] array;
@SuppressWarnings("unchecked")
Container() {
array = (T[])new Object[1];
}
void put(T item) {
array[0] = item;
}
T get() { return array[0]; }
T[] getArray() { return array; }
}
Because of erasure, at runtime, the T[] return type of the getArray() method is turned into a Object[], which is completely reasonable to me.
If we access that method as it is (c.getArray()) no Exceptions are thrown, but if we try to call some methods on the returned array, for example c.Array().getClass(), or if we try to access to a field, for example c.getArray().length, then the following exception is thrown:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
Why is this Exception thrown? Why is it not thrown also for the simple c.getArray() call? Why is it trying to cast to Integer[] if we are simply calling getClass() or accessing length? Are getClass() and length not available also for Object[]?
Thanks in advance for your many (I hope) and explanatory (I hope this too) answers.
c.getArray()
, a reference to it has to be stored on the stack temporarily. I can imagine that JLS says - somewhere, still looking - that this temporary variable has to be checked to see if it is the unerased type (since you know the unerased type there).static <T> void foo(Container<T> c) { c.getArray().getClass(); }
<Integer>
to<Object>
: withInteger
, there is acheckcast
instruction (the reason for theClassCastException
); withObject
, nocheckcast
instruction is added. Understandable, since allT[]
can be cast toObject[]
; just faintly surprising that it results in different bytecode.Integer[]
at the call site ofgetArray()
is no different, linguistically, than the cast toInteger
at the call site ofget()
. (This, BTW, is whyCollection.toArray()
returnsObject[]
rather thanT[]
-- it doesn't want to lie to you and say it's returning anInteger[]
when really it's returning anObject[]
.)