java - 如何在 Java 中正确定义链表数组?

标签 java arrays linked-list

<分区>

我尝试在 Java 中定义一个链表数组,如下所示,它编译正常,但生成了 2 条警告消息。

 LinkedList<Long> [] hashtable = new LinkedList[10];

warning: [rawtypes] found raw type: LinkedList
    LinkedList<Long> [] hashtable = new LinkedList[10];
                                        ^
  missing type arguments for generic class LinkedList<E>
  where E is a type-variable:
    E extends Object declared in class LinkedList
HashTable.java:13: warning: [unchecked] unchecked conversion
    LinkedList<Long> [] hashtable = new LinkedList[10];
                                    ^
  required: LinkedList<Long>[]
  found:    LinkedList[]

所以,我试过了

 LinkedList<Long> [] hashtable = new LinkedList<Long>[10];

但是这次它甚至不会编译并产生这个错误。

HashTable.java:13: error: generic array creation
    LinkedList<Long> [] hashtable = new LinkedList<Long>[10];
                                    ^
1 error

那么,我应该如何正确定义我的链表数组呢?

最佳答案

这是创建数组的正确方法:

@SuppressWarnings("unchecked") LinkedList<Long> [] hashtable = new LinkedList[10];

无法创建参数化类型的数组

您不能创建参数化类型的数组。例如,以下代码无法编译:

List<Integer>[] arrayOfLists = new List<Integer>[2];  // compile-time error

以下代码说明了将不同类型插入数组时发生的情况:

Object[] strings = new String[2];
strings[0] = "hi";   // OK
strings[1] = 100;    // An ArrayStoreException is thrown.

如果你用通用列表尝试同样的事情,就会有问题:

Object[] stringLists = new List<String>[];  // compiler error, but pretend it's allowed
stringLists[0] = new ArrayList<String>();   // OK
stringLists[1] = new ArrayList<Integer>();  // An ArrayStoreException should be thrown,
                                            // but the runtime can't detect it.

如果允许参数化列表的数组,前面的代码将无法抛出所需的 ArrayStoreException

取自docs.oracle.com

那么我可以在 hashtable[] 中存储什么?

Does it mean I am now allowed to have a linked list of string in the hashtable[0] and a linked list of Long in hashtable1, if I do LinkedList [] hashtable = new LinkedList[10]?

不,编译器不允许您将 LinkedList 直接存储到哈希表数组中。以下代码段无法编译:

hashtable[0] = new LinkedList<String>();

然而,您可以存储没有类型参数的 LinkedList,甚至是 LinkedList 的子类:

@SuppressWarnings("unchecked") LinkedList<Long>[] hashtable = new LinkedList[10];

hashtable[0] = new LinkedList<Long>();
hashtable[1] = new MyLinkedList<Long>();
hashtable[2] = new LinkedList();
hashtable[3] = new MyLinkedList();

如果将数组转换为 LinkedList[],则可以存储 LinkedList。但是,除了 LinkedList 之外,您将无法存储任何其他内容:

LinkedList[] rawHashTable = hashtable;
rawHashTable[4] = new LinkedList<String>();

Object[] objectHashTable = rawHashTable;
objectHashTable[5] = "This line will throw an ArrayStoreException ";

关于java - 如何在 Java 中正确定义链表数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27654229/

相关文章:

c# - 如何确定给定文件是类文件?

java - 将 m.group(1) 转换为字符串数组

data-structures - 使用数组实现链表 - 优点和缺点

java - 从递归方法中删除输入

java - 有没有办法确保请求来自受信任的 UI 应用程序?

java - collat​​z 序列 - 优化代码

创建两个指针?字符 *名称[] = {"xxx", "yyy"}

C++ 类和链表 : adding & counting items

c - 在 C 中操作链表时如何解决这个段错误问题?

java - 什么是NullPointerException,我该如何解决?