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

时间:2021-04-24 21:17:54

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];
    }
}

2 个解决方案

#1


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];
    }
}

Here is a good explanation, without getting into the technical details of why generic array creation isn't allowed.

这里有一个很好的解释,但没有深入了解为什么不允许通用数组创建的技术细节。

#2


Also, you can suppress the warning on a method by method basis using annotations:

此外,您可以使用注释逐个方法地抑制警告:

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

#1


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];
    }
}

Here is a good explanation, without getting into the technical details of why generic array creation isn't allowed.

这里有一个很好的解释,但没有深入了解为什么不允许通用数组创建的技术细节。

#2


Also, you can suppress the warning on a method by method basis using annotations:

此外,您可以使用注释逐个方法地抑制警告:

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