初始化泛型类型的 Java 泛型数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1025837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize Java Generic Array of Type Generic
提问by dreadwail
So I have this general purpose HashTable class I'm developing, and I want to use it generically for any number of incoming types, and I want to also initialize the internal storage array to be an array of LinkedList's (for collision purposes), where each LinkedList is specified ahead of time (for type safety) to be of the type of the generic from the HashTable class. How can I accomplish this? The following code is best at clarifying my intent, but of course does not compile.
所以我有我正在开发的这个通用 HashTable 类,我想将它一般用于任意数量的传入类型,我还想将内部存储数组初始化为 LinkedList 的数组(用于冲突目的),其中每个 LinkedList 都提前(为了类型安全)指定为来自 HashTable 类的泛型类型。我怎样才能做到这一点?以下代码最能阐明我的意图,但当然不能编译。
public class HashTable<K, V>
{
private LinkedList<V>[] m_storage;
public HashTable(int initialSize)
{
m_storage = new LinkedList<V>[initialSize];
}
}
回答by Avi
Generics in Java doesn't allow creation of arrays with generic types. You can cast your array to a generic type, but this will generate an unchecked conversion warning:
Java 中的泛型不允许创建具有泛型类型的数组。您可以将数组转换为泛型类型,但这会生成未经检查的转换警告:
public class HashTable<K, V>
{
private LinkedList<V>[] m_storage;
public HashTable(int initialSize)
{
m_storage = (LinkedList<V>[]) new LinkedList[initialSize];
}
}
Hereis a good explanation, without getting into the technical details of why generic array creation isn't allowed.
这是一个很好的解释,没有深入了解为什么不允许创建通用数组的技术细节。
回答by Lawrence Dol
Also, you can suppress the warning on a method by method basis using annotations:
此外,您可以使用注释逐个方法地抑制警告:
@SuppressWarnings("unchecked")
public HashTable(int initialSize) {
...
}

