Reputation: 1798
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?
Upvotes: 1
Views: 230
Reputation: 100050
Start by asking yourself: 'Do I really need an array? Could I just use ArrayList<EntryRecipient<K, V>>
? An array list is a very skinny wrapper on an array; your code has to be awfully performance-sensitive to see any different in speed. Whereas, all this generic type stuff just works.
Upvotes: -3
Reputation: 904
I cannot find any reason for using an Object[]
for EntryRecipient<K,V>[]
in this code. The reference of the array is not a generic reference, so use the array of that class type. Converting an Object array to EntryRecipient
array directly is not possible in Java. (EntryRecipient[]
is not same as T[]
). The solution for your problem is modifying your HashTable
constructor as shown below:
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>();
}
}
Upvotes: 5