Can anyone explain to me why this happens:
public class Array<E> {
public E[] elements = (E[]) new Object[10];
public E get(int idx) {
return elements[idx]; // Ignore bound-checking for brevity.
}
public static void doSomething(Array<Integer> arr) {
Integer good = arr.get(0);
Integer bad1 = arr.elements[0];
Integer bad2 = ((Integer[]) arr.elements)[0];
Integer bad3 = (Integer) arr.elements[0];
// `bad1', `bad2', and `bad3' all produce a
// runtime exception.
}
public static void main(String[] args) {
Array<Integer> test = new Array<>();
Array.doSomething(test);
}
}
Full example here: http://pastebin.com/et7sGLGW
I've read about type erasure and realize type-checking is performed during compilation and then E
is simply replaced with Object
, so all we have is public Object[] elements
, but why does the get
method succeed where regular type-casting doesn't? Doesn't the get
's method return type also get erased?
Thanks.