Can someone please explain to me why the line marked //this line gives a compile error (why?) in the following code sample does not work?
import java.util.ArrayList;
public class GenericCastCheck {
class A{
}
class B extends A{
}
public static void main(String[] args) {
A aObject = new A();
B bObject = new B();
//this line works fine
aObject = bObject;
//this line gives a compile (expected)
bObject = aObject;
ArrayList<A> aList = new ArrayList<A>();
ArrayList<B> bList = new ArrayList<B>();
//this line gives a compile error (why?)
aList = bList;
//this line gives a compile error (expected)
bList = aList;
}
}
Specifically, when we say that bList is of type ArrayList<B>, does it not mean that each element of it is an instance of B? If so, then what is the problem in casting it to ArrayList<A>, if we can cast individual instances of B to A?
Thanks.
The problem is this:
If you do the same thing with arrays, you get an ArrayStoreException in line 4 at runtime. For generic collections, it was decided to prevent that kind of thing at compile time.