sasidhar
sasidhar

Reputation: 7752

Object array not getting cast to a generic type

I intend to create a simple Dictionary ADT using a linked list. I have got little problem with the getKeys() method, here is my code:

@Override
public K[] getKeys() 
{
    if(head==null)
    return null;
    else
    {
        Vector<K> v = new Vector();
        ListNode<K,V> temp= head;
        while(temp!=null)
        {
            v.add(temp.key);
            temp=temp.next;
        }
        //K keys[] = new O[v.size()];

        return (K[])v.toArray();//run time error
    }
}

I am having the following error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
    at Dictionary.ListDictionary.getKeys(ListDictionary.java:17)
    at Dictionary.DictionaryDriver.test(DictionaryDriver.java:83)
    at Dictionary.DictionaryDriver.main(DictionaryDriver.java:107)
Java Result: 1

Here is the interface i am trying to implement:

public interface DictionaryInterface <K extends Comparable<K>, V>
{
    public void insert(K key, V value);
    public V getValue(K str);
    public void remove(K key);
    public K[] getKeys();   
}

I understand that we cannot create an array of generics, but i never had problem with casting generic types to Objecttype.Does it have something to do with the generic type K extending Comparable? How do i work around this??

Upvotes: 2

Views: 589

Answers (1)

Costi Ciudatu
Costi Ciudatu

Reputation: 38195

Try something like:

return (K[])v.toArray(new Comparable[v.size()]);

As a side note, however, mixing generics and arrays is not the best idea.


To do this safely (and be able to accept types other than Comparable), you would need to get the type reference, so your constructor could look like this:

public Dictionary(Class<K> keyType) {
    this.keyType = keyType;
}

Later on, when instantiating that array, call:

return (K[]) v.toArray( Array.newInstance(keyType, v.size()) );

Upvotes: 3

Related Questions