user4173497
user4173497

Reputation:

Cast generic collection an array

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?

Upvotes: 0

Views: 87

Answers (1)

Krease
Krease

Reputation: 16215

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.

Upvotes: 1

Related Questions