问题描述
我的一个班级需要根据他们的超类来存储班级。为此,我使用了一个HashMap,其中键是超类,并且为它们的扩展类列出了一个值。所以看起来像这样:
pre $ HashMap< Class ,List
我想知道是否有一个符号允许我更精确,如下所示:
HashMap< Class< T>,List< Class< ;?延伸T>>>
我试过了,当然,它不起作用:T无法解析。有没有一种语法可以让我做到这一点?感谢您的帮助。
您可以使用访问器方法来完成这项工作。
//只能通过检查键和值的方法访问它们是正确的类型。
final Map< Class,List< Class>> map = new LinkedHashMap< Class,List< Class>>();
public< T,S扩展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扩展T> List< Class< S>> get(Class< T> key){
return(List< Class< S>)map.get(key);
}
public< T,S扩展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); //编译
m.add(Number.class,String.class); //不编译。
}
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.
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.
}
这篇关于HashMap< Class<>,List< Class<>>> :指定列表的'类扩展键'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!