Initialize Java Generic Array of Type Generic

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.

Leave a Comment