Consider the following code:
class AA { }
class BB extends AA { }
public class Testing {
public static void main(String[] args) {
BB[] arr = new BB[10];
AA[] arr2 = arr;
BB b = new BB();
AA a = new AA();
arr2[0] = a; // ArrayStoreException at runtime
arr2[1] = b;
List<BB> listBB = new ArrayList<>();
List listAA = listBB;
listAA.add("hello world.txt");
}
}
In the above example, I get the ArrayStoreException
when I try arr2[0] = a
. That means the array remembers what type it must accept. But the List
does not remember them. It simply compiles and runs fine. The ClassCastException
will be thrown when I retrieve the object BB
.
So the questions are:
How an array remembers its type (I know it's called "reification"). How this happens exactly?
And why only arrays are bestowed with this power but not
ArrayList
although it uses an array under its hood.Why can't
ArrayStoreException
be detected at compile time, i.e when I doarr2[0] = a
, it could cause a compiler error, instead of detecting it at runtime.
Thanks.