I'm trying to implement a separate chained hashtable in Java, and I encountered with the classcastexception.
so here is what I did:
private LinkedList<Entry<K,V>>[] bucketArray; This array is going to hold all the linkedlist which will serve as chains. There is also an inner class Entry in the class HashTable each holding a K generic key, and V generic value.
In the contructor for the table I actually initialze the array:
public HashTable(int capacity, int prime) { this.capacity = capacity; this.prime = prime; bucketArray = (LinkedList<Entry<K, V>>[]) new Object[this.capacity]; } So prime is just gonne be used for calculating compressed key, capacity is for array size. but as I run that jvm throws classcastexception.
If I change new Object to new LinkedList [this.capacity], then I have a nullpointer exception in my put method which looks like this:
public void put(K k, V v) { int h = hashValue(k); bucketArray[h].add(new Entry<K, V>(k, v)); } for the sake of simplicity hashvalue method always returns 1.
How could it be done properly?