This works:
static class HashMap {
private final int initialCapacity;
private final double loadFactor;
private List<Data<Character, Integer>> [] table;
public HashMap() {
this.initialCapacity = 16;
this.loadFactor = 0.75;
table = (List<Data<Character, Integer>> [])new Object[initialCapacity];
}
}
This doesn't work (gives a generic array creation error):
static class HashMap<K, V> {
private final int initialCapacity;
private final double loadFactor;
private List<Data<K, V>> [] table;
public HashMap() {
this.initialCapacity = 16;
this.loadFactor = 0.75;
table = (List<Data<K, V>> [])new Object[initialCapacity];
}
}
How do I get the second version to work?
As you can probably tell, I'm trying to implement a generic HashMap for fun. The Data class is just a simple, custom tuple class that I wrote, and I would like my HashMap to function with any key/value types that the user may provide. The table array is an array of linked lists that contain tuples (basically a hash table). NOTE: The List class here is NOT the built-in Java List class, it is also a class that I WROTE MYSELF!
There are some questions on SO regarding the generic array creation error, but none of them address this kind of scenario. Any ideas are appreciated!
P.S Here's the Data class in case anyone wants to test out the code:
static class Data<K, V> {
private final K key;
private final V value;
public Data(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!Data.class.isAssignableFrom(obj.getClass()))
return false;
final Data<K, V> b = (Data<K, V>) obj;
return this.key.equals(b.getKey());
}
}