运行时错误:Java中带有泛型的列表数组

时间:2021-01-19 21:20:30

I'm attempting the following to implement a separate chaining hash table with generics:

我正在尝试以下实现一个单独的链接哈希表与泛型:

// hash table class
protected List<HashEntry<K, V>>[] bucket;
this.bucket = (List<HashEntry<K, V>>[]) new Object[capacity];(*)
(...)
// main program
HashTableMapSC<Integer, String> hashSC = new HashTableMapSC<Integer,String>(7);

I get the following run-time error:

我收到以下运行时错误:

[Ltablashash.HashTableMapSC$HashEntry; cannot be cast to [Ljava.util.List;

[Ltablashash.HashTableMapSC $ HashEntry;无法转换为[Ljava.util.List;

located at (*)

位于 (*)

HashEntry is just a simple private class that holds key,pair values.

HashEntry只是一个包含键值对的简单私有类。

I'm aware that this would work:

我知道这会起作用:

protected List<List<HashEntry<K,V>>> bucket;

but as I'm been asked to do it that way,I would like to know if it's possible.

但是当我被要求这样做时,我想知道它是否可能。

Thanks

谢谢

1 个解决方案

#1


2  

If you definitely need an array of generics (which is usually discouraged), use

如果你肯定需要一系列泛型(通常不鼓励),请使用

this.bucket = new List[capacity];

You will have a rawtypes warning though.

你会有一个rawtypes警告。

#1


2  

If you definitely need an array of generics (which is usually discouraged), use

如果你肯定需要一系列泛型(通常不鼓励),请使用

this.bucket = new List[capacity];

You will have a rawtypes warning though.

你会有一个rawtypes警告。