I am trying to implement a basic hashmap in Java and am stuck on why I cannot declare an array of my custom class KVPair. I am getting an error after numerous trials of fixing my declaration of the array in my constructor:
contains = new KVPair[capacity];
When I tried this, I got a compile error saying that I "cannot create a generic array of HashMap.KVPair."
I have also seen from another stackexchange answer that suggested casting an array of objects into something else like this:
contains = (KVPair[])new Object[capacity];
When I do this, I get a run-time error saying "java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [MyHashMap$KVPair;."
Below I have included one of the constructors of my hashmap class as well as my KVPair class. Any help on how I can solve this issue would be much appreciated.
public class MyHashMap<K, V> implements Iterable<K> {
private static final int DEFAULT_CAPACITY = 200;
private static final double DEFAULT_LOAD_FACTOR = 0.7;
private int capacity; // the number of buckets in the map
private int size; // the number of items that have been put into the map
private double loadFactor;
KVPair[] contains;
// Constructs an empty map.
public MyHashMap() {
capacity = DEFAULT_CAPACITY;
this.loadFactor = DEFAULT_LOAD_FACTOR;
contains = (KVPair[]) new Object[capacity];
}
...
public class KVPair {
private K key;
private V value;
private KVPair next;
private int hash;
private KVPair(Object k, Object v){
key = (K) k;
value = (V) v;
next = null;
hash = k.hashCode();
}
public KVPair(Object k, Object v, KVPair nextKV){
key = (K) k;
value = (V) v;
next = nextKV;
hash = k.hashCode();
}
}