I think there must be something subtle going on here that I don’t know about. Consider the following:
public class Foo<T> { private T[] a = (T[]) new Object[5]; public Foo() { // Add some elements to a } public T[] getA() { return a; } }
Suppose that your main method contains the following:
Foo<Double> f = new Foo<Double>(); Double[] d = f.getA();
You will get a CastClassException with the message java.lang.Object cannot be cast to java.lang.Double.
Can anyone tell me why? My understanding of ClassCastException is that it is thrown when you try to cast an object to a type that cannot be casted. That is, to a subclass of which it is not an instance (to quote the documentation). e.g.:
Object o = new Double(3.); Double d = (Double) o; // Working cast String s = (String) o; // ClassCastException
And it seems I can do this. If a was just a T instead of an array T[], we can get a and cast it without a problem. Why do arrays break this?
Thanks.
When you use this version of the generic class Foo, then for the member variable
a, the compiler is essentially taking this line:and replacing
TwithDoubleto get this:You cannot cast from Object to Double, hence the ClassCastException.
Update and Clarification: Actually, after running some test code, the ClassCastException is more subtle than this. For example, this main method will work fine without any exception:
The problem occurs when you attempt to assign
f.getA()to a reference of typeDouble[]:This is because the type-information about the member variable
ais erased at runtime. Generics only provide type-safety at compile-time (I was somehow ignoring this in my initial post). So the problem is notbecause at run-time this code is really
The problem occurs when the result of method
getA(), which at runtime actually returns anObject[], is assigned to a reference of typeDouble[]– this statement throws the ClassCastException because Object cannot be cast to Double.Update 2: to answer your final question ‘why do arrays break this?’ The answer is because the language specification does not support generic array creation. See this forum post for more – in order to be backwards compatible, nothing is known about the type of T at runtime.