简体   繁体   English

Java:了解通用数组的类型擦除

[英]Java: Understanding Type Erasure with Generic Arrays

I was wondering whether I understand the following Java issue correctly. 我想知道我是否正确理解以下Java问题。 Given a generic collection, if I do 给定一个通用集合,如果我这样做

public class HashTable<V extends Comparable<V>> implements HashTableInterface<V> {
    private V[] array;

    public HashTable() {
        this.array = (V[]) new Object[10];
    }
}

the code breaks, throwing an exception: java.lang.ClassCastException: [Ljava.lang.Object; 代码中断,并引发异常:java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable; 无法转换为[Ljava.lang.Comparable;

However, if I change this.array = (V[]) new Object[10]; 但是,如果我更改this.array = (V[]) new Object[10]; to this.array = (V[]) new Comparable[10]; this.array = (V[]) new Comparable[10]; then it works. 然后就可以了。

The way I understand it is that upon compilation the resulting bytecode will not have any generic references as they are replaced by Java's type erasure. 我的理解是,编译后生成的字节码将没有任何泛型引用,因为它们已被Java的类型擦除所取代。

this.array = (V[]) new Object[10]; breaks because the line will implicitly be replaced by this.array = (Comparable[]) new Object[10]; 中断,因为该行将被this.array = (Comparable[]) new Object[10];隐式替换this.array = (Comparable[]) new Object[10]; which will then result in a cast exception as Object does not extend Comparable. 这将导致强制转换异常,因为Object不扩展Comparable。 It is resolved by changing it to an array of Comparables. 通过将其更改为可比较数组来解决。

Is this correct? 这个对吗? Thanks! 谢谢!

The type variable is erased to the erasure of its left most bound. 擦除类型变量以消除其最左边界 So V is erased to |Comparable<V>| = Comparable 因此, V被擦除为|Comparable<V>| = Comparable |Comparable<V>| = Comparable . |Comparable<V>| = Comparable If you changed the bound to Object & Comparable<V> the erasure would become |Object| = Object 如果将边界更改为Object & Comparable<V>则擦除将变为|Object| = Object |Object| = Object and (V[]) new Object[10] would work also. |Object| = Object(V[]) new Object[10]也将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM