Java Generics: Array containing generics [duplicate]

只谈情不闲聊 提交于 2019-11-30 20:18:38

This worked for me:

public class HashTable<T> {

    private LinkedList<T> table[];

    @SuppressWarnings("unchecked")
    public HashTable(int size) {
        table = new LinkedList[size];
    }

}

For example:

HashTable<String> t = new HashTable<String>(10);
t.table[0] = new LinkedList<String>();
t.table[0].add("test");
System.out.println(t.table[0].get(0));

Yes, the constructor generated a warning (that explains the "unchecked" annotation), but afterwards the code works without more warnings.

Just use Object[] as your data store, and manually cast it to the specific type. This is acceptable in building infrastructure stuff, where type relations can be harder than usual.

For what it's worth, this is the way to create generic array in Java:

@SafeVarargs
static <E> E[] newArray(int length, E... array)
{
    return Arrays.copyOf(array, length);
}

//used in your example

    private LinkedList<T>[] table;

    public HashTable(int size) {
        table = newArray(size);
    }

It isn't ideal, but you can do this sort of thing:

import java.util.LinkedList;

public class Test
{
    static class HashTable<T>
    {
        public HashTable(int size)
        {
            LinkedList<T>[] table = (LinkedList<T>[])java.lang.reflect.Array.newInstance(LinkedList.class, size);
        }
    }

    public static void main(String[] args)
    {
        HashTable<Integer> table = new HashTable<Integer>(23);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!