Search code examples
javagenericstoarray

Create generic array for toArray method


I have this following method:

public static <T, U> T[] getKeysForValue(Map<T,U> map,U value){
    if(map == null || map.isEmpty()) {
        return null;
    }

    Set<T> keys = new HashSet<T>();

    for (Map.Entry<T,U> entry : map.entrySet()) {
        if (entry.getValue().equals(value)) {
            keys.add(entry.getKey());
        }
    }

    return keys.toArray(new T[keys.size()]);
}

I am getting compilation error on the line: keys.toArray(new T[keys.size()]), which says "Cannot create a generic array of T", which is obvious. How can I solve this issue?


Solution

  • You should pass the class corresponding to T as argument of your method and call Array.newInstance(clazz, size)

    public static <T, U> T[] getKeysForValue(Class<T> clazz, Map<T,U> map,U value){
    
      T[] array = (T[])Array.newInstance(clazz, size);