[英]Why doesn't type erasure work with arrays in Java?
I noticed we're unable to create arrays of a generic type in Java, like below: 我注意到我们无法在Java中创建通用类型的数组,如下所示:
public class ExampleClass<G> {
private G[] genericArray = new G[arraySize];
}
I've read that this is due to the way Java handles generics, using type erasure. 我已经读到这是由于Java使用类型擦除来处理泛型的方式。 My understanding of type erasure is that the generic is just replaced by the most specific superclass container - so if we provide no bound, every instance of
G
is just replaced by Object
. 我对类型擦除的理解是,泛型仅被最特定的超类容器替换-因此,如果我们不提供绑定,则
G
每个实例都将被Object
替换。
Why can't this be done with the array, creating an array of type Object
? 为什么不能使用创建
Object
类型数组的数组来完成此操作?
If this were allowed, and G
were erased to Object
, then the following wouldn't work: 如果允许这样做,并且
G
被擦除为Object
,那么以下操作将无效:
ExampleClass<String> foo = new ExampleClass<>();
String[] array = foo.genericArray;
because genericArray
would be an Object[]
, not a String[]
. 因为
genericArray
将是一个Object[]
,而不是String[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.