Initialize Java Generic Array of Type Generic

后端 未结 2 819
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 13:51

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

相关标签:
2条回答
  • 2020-11-30 14:47

    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.

    0 讨论(0)
  • 2020-11-30 14:52

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

    @SuppressWarnings("unchecked")
    public HashTable(int initialSize) {
        ...
        }
    
    0 讨论(0)
提交回复
热议问题