且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-09 21:48:11

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

This is a proper way to create an array:

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

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

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

Cannot Create Arrays of Parameterized Types

You cannot create arrays of parameterized types. For example, the following code does not compile:

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

以下代码说明了将不同类型插入数组时会发生什么:

The following code illustrates what happens when different types are inserted into an array:

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

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

If you try the same thing with a generic list, there would be a problem:

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.

If arrays of parameterized lists were allowed, the previous code would fail to throw the desired ArrayStoreException.

取自 docs.oracle.com

这是否意味着我现在可以在hashtable[0] 和一个 Long in hashtable 的链表1,如果我这样做LinkedList [] hashtable = new LinkedList[10]?

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 存储到哈希表数组.以下代码段无法编译:

No, compiler won't allow you to store LinkedList to the hashtable array directly. Following snippet won't compile:

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

然而,你可以不带类型参数存储 LinkedList,甚至可以存储 LinkedList 的子类:

However you can store the LinkedList without type parameters, or even a subclass of 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 之外,您将无法存储其他任何内容:

You can store the LinkedList if you cast your array to LinkedList[]. However you won't be able to store the anything else but a LinkedList:

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

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