I have seen in many answers (e.g., this) that a way of creating an array using generics is the following:
T[] array = (T[]) new Object[SIZE];
I am trying to do something similar:
EntryRecipient<K,V>[] array = (EntryRecipient<K,V>[]) new Object[MAX_SIZE];
However, this does not work, casting the following error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LHashTable$EntryRecipient;
My code is:
HashTableEntry (included as private subclass of 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;
}
}
EntryRecipient (included as private subclass of HashTable)
private class EntryRecipient<K,V> {
private List<HashTableEntry<K,V>> entries;
public EntryRecipient() {
entries = new ArrayList<HashTableEntry<K,V>>();
}
// ... other methods
}
HashTable
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
}
Could you give me some hints to solve this?