Java: Understanding Type Erasure with Generic Arrays

天大地大妈咪最大 提交于 2019-12-12 00:50:23

问题


I was wondering whether I understand the following Java issue correctly. 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; cannot be cast to [Ljava.lang.Comparable;

However, if I change this.array = (V[]) new Object[10]; to 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.

this.array = (V[]) new Object[10]; breaks because the line will implicitly be replaced by this.array = (Comparable[]) new Object[10]; which will then result in a cast exception as Object does not extend Comparable. It is resolved by changing it to an array of Comparables.

Is this correct? Thanks!


回答1:


The type variable is erased to the erasure of its left most bound. So V is erased to |Comparable<V>| = Comparable. If you changed the bound to Object & Comparable<V> the erasure would become |Object| = Object and (V[]) new Object[10] would work also.



来源:https://stackoverflow.com/questions/12137097/java-understanding-type-erasure-with-generic-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!