简体   繁体   English

初始化类型Generic的Java通用数组

[英]Initialize Java Generic Array of Type Generic

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. 所以我有这个我正在开发的通用HashTable类,我想将它一般用于任意数量的传入类型,我想将内部存储数组初始化为LinkedList的数组(用于冲突),其中每个LinkedList都是提前指定的(对于类型安全性),它是HashTable类中泛型的类型。 How can I accomplish this? 我怎么能做到这一点? The following code is best at clarifying my intent, but of course does not compile. 以下代码最能说明我的意图,但当然不能编译。

public class HashTable<K, V>
{
    private LinkedList<V>[] m_storage;

    public HashTable(int initialSize)
    {
        m_storage = new LinkedList<V>[initialSize];
    }
}

Generics in Java doesn't allow creation of arrays with generic types. Java中的泛型不允许创建具有泛型类型的数组。 You can cast your array to a generic type, but this will generate an unchecked conversion warning: 您可以将数组转换为泛型类型,但这会生成未经检查的转换警告:

public class HashTable<K, V>
{
    private LinkedList<V>[] m_storage;

    public HashTable(int initialSize)
    {
        m_storage = (LinkedList<V>[]) new LinkedList[initialSize];
    }
}

Here is a good explanation, without getting into the technical details of why generic array creation isn't allowed. 这里有一个很好的解释,但没有深入了解为什么不允许通用数组创建的技术细节。

Also, you can suppress the warning on a method by method basis using annotations: 此外,您可以使用注释逐个方法地抑制警告:

@SuppressWarnings("unchecked")
public HashTable(int initialSize) {
    ...
    }

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

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