views:

2183

answers:

3

So I have this general purpose HashTable class I'm developing, and I want to use it generically for any number of incoming types, and I want to also initialize the internal storage array to be an array of LinkedList's (for collision purposes), where each LinkedList is specified ahead of time (for type safety) to be of the type of the generic from the HashTable class. How can I accomplish this? The following code is best at clarifying my intent, but of course does not compile.

public class HashTable<K, V>
{
    private LinkedList<V>[] m_storage;

    public HashTable(int initialSize)
    {
        m_storage = new LinkedList<V>[initialSize];
    }
}
+7  A: 

Generics in Java doesn't allow creation of arrays with generic types. You can cast your array to a generic type, but this will generate an unchecked conversion warning:

public class HashTable<K, V>
{
    private LinkedList<V>[] m_storage;

    public HashTable(int initialSize)
    {
        m_storage = (LinkedList<V>[]) new LinkedList[initialSize];
    }
}

Here is a good explanation, without getting into the technical details of why generic array creation isn't allowed.

Avi
+1 Thanks for the great response and resource.
byte
You can add @SuppressWarnings({"unchecked"}) to the assignment to keep the compiler quiet.
Aaron Digulla
A: 

May be i dont understand your question but you seem to be doing what is already there. A HashTable already has generic support K,V?

You could give some more information about the problem you are trying to solve

Ngetha
There is no other purpose or problem than learning. You can't learn how a HashTable is best implemented by using one like a black box.
byte
A: 

Also, you can suppress the warning on a method by method basis using annotations:

@SuppressWarnings("unchecked")
public HashTable(int initialSize) {
    ...
    }
Software Monkey