HashMap<Class<?>, List<Class<?>>> : specify that the lists' classes extend the keys'

牧云@^-^@ 提交于 2019-12-21 09:29:04

问题


One of my class need to store classes according to their superclasses. To that end, I'm using a HashMap, where keys are the superclasses, and values a list of their extended classes. So it looks like that :

HashMap<Class<?>, List<Class<?>>>

I'd like to know if there was a notation allowing me to be more precise, something like :

HashMap<Class<T>, List<Class<? extends T>>>

I've tried that and, of course, it doesn't work : T cannot be resolved. Is there a syntax that would allow me to do that ? Thanks in advance for your help.


回答1:


You can do that with accessor methods.

// only accessed by methods which check the keys and values are the right type.
final Map<Class, List<Class>> map = new LinkedHashMap<Class, List<Class>>();

public <T, S extends T> void add(Class<T> key, Class<S> value) {
    List<Class> list = map.get(key);
    if (list == null)
        map.put(key, list = new ArrayList<Class>());
    list.add(value);
}

public <T, S extends T> List<Class<S>>get(Class<T> key) {
    return (List<Class<S>>) map.get(key);
}

public <T, S extends T> boolean contains(Class<T> key, Class<S> value) {
    List<Class> list = map.get(key);
    if (list == null) return false;
    return list.contains(value);
}

public static void main(String... args) {
    Main m = new Main();
    m.add(Number.class, Integer.class); // compiles
    m.add(Number.class, String.class); // does not compile.
}



回答2:


Something like:

class MyMap<T extends Class<?>> extends HashMap<T, List<T>> {

}

Won't entirely solve your problem. You can see that on single entries in the map it cannot vary.



来源:https://stackoverflow.com/questions/8184049/hashmapclass-listclass-specify-that-the-lists-classes-extend-the-k

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!