سؤال

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?

هل كانت مفيدة؟

المحلول 2

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);

نصائح أخرى

Why not just return the Set? That seems to make more sense in this context anyway.

public static <T, U> Set<T> getKeysForValue(Map<T, U> map, U value) {
    ...

    return keys;
}

An alternative, if you still want to return an array, would be to pass an array to be filled as an argument:

public static <T, U> T[] getKeysForValue(Map<T,U> map, U value, T[] dest) {
    ...

    return keys.toArray(dest);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top