[英]Java :How Generic Erasure Works
Scenario A.java-----------after erasure-------->M.class
方案A.java -----------擦除后--------> M.class
Scenario B.java-----------after erasure-------->M.class
场景B.java -----------擦除后--------> M.class
Then why A is illegal and B is legal since they have almost the same M after erasure. 那么为什么A是非法的而B是合法的,因为擦除后它们的M几乎相同。
Scenario A before erasure: 擦除前的方案A:
class ArrayList<V> {
private V[] backingArray;
public ArrayList() {
backingArray = new V[DEFAULT_SIZE]; // illegal
}
}
Scenario A after erasure: 擦除后的方案A:
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: 实际上,Object [Default_Size]是有用的〜擦除前的情况B:
class ArrayList<V> {
private V[] backingArray;
public ArrayList() {
backingArray = (V[]) new Object[DEFAULT_SIZE];
}
}
Scenario B after erasure: 删除后的情况B:
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. 方案A非法的原因是Java的协变量数组不是通过擦除实现的。 This:
这个:
Object[] foo = new String[4];
foo[0] = new Object();
will raise an ArrayStoreException
at run-time, because foo
refers to an array instance that knows it's a String[]
(even though it's referred to via the variable foo
, which has compile-time type Object[]
). 将在运行时引发
ArrayStoreException
,因为foo
表示知道它是String[]
的数组实例(即使它是通过具有编译时类型Object[]
的变量foo
引用的)。 So this: 所以这:
new V[4]
is illegal, because the run-time won't know what type of array instance to create. 这是非法的,因为运行时不知道要创建哪种类型的数组实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.