7

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];
    }
}
dreadwail
  • 13,965
  • 21
  • 60
  • 91

2 Answers2

15

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
  • 19,313
  • 3
  • 53
  • 69
  • You can add @SuppressWarnings({"unchecked"}) to the assignment to keep the compiler quiet. – Aaron Digulla Jun 22 '09 at 08:00
  • The page you linked to is actually not about the same thing. [This section](http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104) of Angelika Langer's Generics FAQ explains it well. – Paul Bellora Nov 08 '12 at 20:11
  • If you use `@SuppressWarnings({"unchecked"})` before this command to keep the compiler quiet, you can also just do `@SuppressWarnings({"unchecked"}) m_storage = new LinkedList[initialSize];` which is a bit simpler and technically no difference to `@SuppressWarnings({"unchecked"}) m_storage = (LinkedList[]) new LinkedList[initialSize];`. But I have to agree: neither of those are really nice :-( – Daniel Alder Nov 03 '13 at 12:11
  • 1
    The link to the explanation is broken – Daniel Alder Nov 03 '13 at 12:15
0

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

@SuppressWarnings("unchecked")
public HashTable(int initialSize) {
    ...
    }
Lawrence Dol
  • 59,198
  • 25
  • 134
  • 183