0

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?

1
  • Arrays are initialized with null elements by default. You must check whether your bucketArray[h] contains null and initialize that element with fresh LinkedList instance. Something like if (buckerArray[h] == null) { buckerArray[h] = new LinkedList<Entry<K, V>>(); } before bucketArray[h].add(new Entry<K, V>(k, v)) Commented Jan 23, 2015 at 21:25

1 Answer 1

1

It looks like you're trying to cast an Object[] to a LinkedList[] - that's why you're getting the error. In fact, the cast is not even necessary if you create the right type:

bucketArray = new LinkedList[this.capacity]; 

Your NPE is a different issue - you've allocated the bucketArray, but each item in it is null - you'll probably want to do a null check on bucketArray[h] and assign it to a new LinkedList before trying to add entries to it.

Sign up to request clarification or add additional context in comments.

4 Comments

I changed it the way you linked, but then i got a nullpointerexception in my put method, which I'll add in my comment. I suspect, that that is becasuse the array is not created maybe.
I've updated my answer. If you have more issues related to other methods, it would probably be better to post new questions referring to this one rather than continually adding more questions here.
alleight, thanks for the answers, i removed the cast and now it works fine, thanks for the help again!!
No prob. As it seems you are relatively new to SO, please take a look at What should I do when someone answers my question.