泛型与阵列

Ele*_*ore 1 java arrays generics

我在许多答案(例如,这个)中看到,使用泛型创建数组的方法如下:

T[] array = (T[]) new Object[SIZE];
Run Code Online (Sandbox Code Playgroud)

我想尝试做类似的事情:

EntryRecipient<K,V>[] array = (EntryRecipient<K,V>[]) new Object[MAX_SIZE];
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用,抛出以下错误:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LHashTable$EntryRecipient;
Run Code Online (Sandbox Code Playgroud)

我的代码是:

HashTableEntry(包含在HashTable的私有子类中)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

EntryRecipient(作为HashTable的私有子类包含)

private class EntryRecipient<K,V> {
    private List<HashTableEntry<K,V>> entries;

    public EntryRecipient() {
        entries = new ArrayList<HashTableEntry<K,V>>();
    }

    // ... other methods
}
Run Code Online (Sandbox Code Playgroud)

哈希表

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
}
Run Code Online (Sandbox Code Playgroud)

你能给我一些提示来解决这个问题吗?

Gob*_*ath 5

我在这段代码中找不到使用Object[]for的任何理由EntryRecipient<K,V>[].数组的引用不是通用引用,因此请使用该类类型的数组.EntryRecipient在Java中不可能直接将Object数组转换为数组.(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>();
    }
}
Run Code Online (Sandbox Code Playgroud)