To give you a bit of context, I am trying to build from scratch a HashMap using Java.
I have some issues when I am trying to instantiate an array of Nodes (Private class as defined below). I just want to instantiate the array first (in the constructor) and later I will update the same array (in methods not yet implemented).
Please find below the code to replicate the bug and the error message. Why the line this.array = (K[]) new Object[this.size];
works and the line this.buckets = (Node[]) new Object[this.size];
doesn't work?.
Is this achievable in Java or should I completely rethink the logic?
public class MyHashMapTest<K, V> {
private class Node {
K key;
V val;
Node next;
Node(K k, V v, Node n) {
key = k;
val = v;
next = n;
}
}
private static final double defaultLoadFactor = 0.75;
private static final int defaultSize = 16;
private Node[] buckets;
private K[] array;
private int size;
private int items;
private double loadFactor;
public MyHashMapTest() {
this(defaultSize, defaultLoadFactor);
}
public MyHashMapTest(int initialSize) {
this(initialSize, defaultLoadFactor);
}
public MyHashMapTest(int initialSize, double loadFactor) {
this.size = initialSize;
this.loadFactor = loadFactor;
this.items = 0;
this.array = (K[]) new Object[this.size];
this.buckets = (Node[]) new Object[this.size];
}
public static void main(String[] args) {
MyHashMapTest<String, String> a = new MyHashMapTest<String, String>();
}
}