Scenario A.java———–after erasure——–>M.class
Scenario B.java———–after erasure——–>M.class
Then why A is illegal and B is legal since they have almost the same M after erasure.
Scenario A before erasure:
class ArrayList<V> {
private V[] backingArray;
public ArrayList() {
backingArray = new V[DEFAULT_SIZE]; // illegal
}
}
Scenario A after erasure:
class ArrayList<V> {
private Object[] backingArray;
public ArrayList() {
backingArray = new Object[DEFAULT_SIZE]; // this is not useful
}
}
actually the Object[Default_Size] is useful ~
Scenario B before erasure:
class ArrayList<V> {
private V[] backingArray;
public ArrayList() {
backingArray = (V[]) new Object[DEFAULT_SIZE];
}
}
Scenario B after erasure:
class ArrayList<V> {
private Object[] backingArray;
public ArrayList() {
backingArray = (Object[]) new Object[DEFAULT_SIZE];
}
}
The reason that Scenario A is illegal is that Java’s covariant arrays are not implemented via erasure. This:
will raise an
ArrayStoreExceptionat run-time, becausefoorefers to an array instance that knows it’s aString[](even though it’s referred to via the variablefoo, which has compile-time typeObject[]). So this:is illegal, because the run-time won’t know what type of array instance to create.