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

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

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

问题描述

所以我有这个通用的HashTable类,我正在开发,我希望将它用于任何数量的传入类型,并且我还想将内部存储阵列初始化为LinkedList的数组(为了碰撞目的),其中每个LinkedList被提前指定(用于类型安全)为HashTable类的泛型类型。我怎样才能做到这一点?

  public class HashTable< K,V>以下代码最好说明我的意图,但当然不会编译。 
{
private LinkedList< V> [] m_storage;

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


解决方案

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

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

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

是一个很好的解释,没有深入讨论为什么通用数组创建不是为什么允许。


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];
    }
}
解决方案

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 04:36