Java不允许内部类的数组为一个泛型类 [英] Java doesn't allow arrays of inner classes for a generic class

查看:370
本文介绍了Java不允许内部类的数组为一个泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你不能创建一个泛型类型的数组,相反,你不得不求助于黑客攻击。 (鉴于Java支持通用阵列,只是没有他们的创作,这是对我不清楚为什么一个黑客比Java支持创建通用阵列更好)

I know that you cannot create an array of a generic type, Instead you have to resort to a hack. (Given Java supports generic arrays, just not their creation, it is not clear to me why a hack is better than Java supporting creating generic arrays)

而不是写本

Map.Entry<K, V>[] entries = new Map.Entry<K, V>[numEntries];

你必须写这个

@SuppressWarnings("unchecked")
Map.Entry<K, V>[] entries = (Map.Entry<K, V>) new Map.Entry[numEntries];

不幸的是,如果你有嵌套类型泛型的数组,这并不正常工作

Unfortunately this doesn't work if you have an array of nested type of a generic

public class Outer<E> {
    final Inner[] inners = new Inner[16]; // Generic array creation

    class Inner {
    }
}

最好的变通似乎

@SuppressWarnings("unchecked")
final Inner[] inners = (Inner[]) Array.newInstance(Inner.class, 16);

这是最优雅的解决方案?

Is this the most "elegant" solution?

我把看到的<一个href=\"http://stackoverflow.com/questions/10671723/generic-array-creation-compilation-error-from-inner-class\">Generic数组创建编译错误从内部类但这里的解决方案是恕我直言更糟。

I make seen Generic Array Creation Compilation Error From Inner Class but the solution here is worse IMHO.

推荐答案

执行以下操作:

@SuppressWarnings("unchecked")
final Inner[] inners = (Inner[])new Outer<?>.Inner[16];

等同于你的第一个例子将是新Outer.Inner [16] 但这将隔离选中的演员和避免原始类型。

The equivalent to your first example would have been new Outer.Inner[16] but this will isolate the unchecked cast and avoid the raw type.

这篇关于Java不允许内部类的数组为一个泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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