初始化泛型类型的

初始化泛型类型的

本文介绍了初始化泛型类型的 Java 泛型数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有我正在开发的通用 HashTable 类,我想将它一般用于任意数量的传入类型,并且我还想将内部存储数组初始化为 LinkedList 的数组(用于冲突目的)),其中每个 LinkedList 都提前(为了类型安全)指定为来自 HashTable 类的泛型类型.我怎样才能做到这一点?下面的代码最能阐明我的意图,但当然不能编译.

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.

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

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

推荐答案

Java 中的泛型不允许创建具有泛型类型的数组.您可以将数组强制转换为泛型类型,但这会生成未经检查的转换警告:

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:

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.

这篇关于初始化泛型类型的 Java 泛型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:07