Java:了解使用通用阵列的类型擦除 [英] Java: Understanding Type Erasure with Generic Arrays

查看:98
本文介绍了Java:了解使用通用阵列的类型擦除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否正确理解以下Java问题。给定泛型集合,如果我这样做的话:

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

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

代码中断,引发异常:java.lang .ClassCastException: [Ljava.lang.Object;无法转换为[Ljava.lang.Comparable;



但是,如果我更改 this.array =(V []) new Object [10]; to this.array =(V [])new Comparable [10]; 然后它就可以使用。



我的理解是编译后得到的字节码不会有任何泛型引用,因为它们被Java的类型擦除所取代。



this.array =(V [])new Object [10]; 中断,因为该行将被隐式地替换为 this.array = (Comparable [])new Object [10]; 这将导致抛出异常,因为Object不会扩展Comparable。它通过将其更改为可比较数组来解决。

这是正确的吗?谢谢!

解决方案

类型变量被擦除以擦除其最左边的边界。因此 V 被擦除为 | Comparable< V> | =可比较。如果将边界更改为 Object& Comparable< V> 擦除将变为 | Object | = Object (V [])new Object [10] 也可以。


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!

解决方案

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.

这篇关于Java:了解使用通用阵列的类型擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆