我在许多答案中看到(例如 this ),使用泛型创建数组的方法如下:
T[] array = (T[]) new Object[SIZE];
我正在尝试做类似的事情:
EntryRecipient<K,V>[] array = (EntryRecipient<K,V>[]) new Object[MAX_SIZE];
但是,这不起作用,会出现以下错误:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LHashTable$EntryRecipient;
我的代码是:
HashTableEntry(作为 HashTable 的私有(private)子类包含在内)
class HashTableEntry<K,V> {
private K key;
private V value;
public HashTableEntry(K key, V value) {
this.key = key;
this.value = value;
}
public V value() {
return value;
}
public K key() {
return key;
}
}
EntryRecipient(作为 HashTable 的私有(private)子类包含在内)
private class EntryRecipient<K,V> {
private List<HashTableEntry<K,V>> entries;
public EntryRecipient() {
entries = new ArrayList<HashTableEntry<K,V>>();
}
// ... other methods
}
哈希表
class HashTable<K,V> {
private EntryRecipient<K,V>[] map;
private final int MAX_SIZE = 199; // Prime, to avoid collisions
private int size;
public HashTable() {
map = (EntryRecipient<K,V>[]) new Object[MAX_SIZE];
size = 0;
}
// ... other methods
}
你能给我一些解决这个问题的提示吗?
最佳答案
我找不到任何使用 Object[]
的理由对于 EntryRecipient<K,V>[]
在这段代码中。数组的引用不是通用引用,因此请使用该类类型的数组。将对象数组转换为 EntryRecipient
在Java中直接数组是不可能的。 ( EntryRecipient[]
与 T[]
不同)。您问题的解决方案是修改您的 HashTable
构造函数如下所示:
public HashTable() {
// Create an array of EntryRecipient
map = new EntryRecipient[MAX_SIZE];
size = 0;
// Initialize the array
// Otherwise you will get NullPointerException
for (int i = 0; i < MAX_SIZE; i++) {
map[i] = new EntryRecipient<K, V>();
}
}
关于java - 泛型与数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31367627/