将 Java 泛型与 HashMap 结合使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19275285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Java Generics with HashMap
提问by du-it
I have a class B and C which both extends class A:
我有一个 B 类和 C 类,它们都扩展了 A 类:
public class B extends A {...}
public class C extends A {...}
How can I use Java generics with a HashMap this way?
如何以这种方式将 Java 泛型与 HashMap 一起使用?
B b = new B();
C c = new C();
Map<String, ? extends A> map = new HashMap<String, A>();
map.put("B", b);
map.put("C", c);
Eclipse always shows an error:
Eclipse 总是显示错误:
The method put(String, capture#1-of ? extends A) in the type Map is not applicable for the arguments (String, B)
类型 Map 中的 put(String, capture#1-of ? extends A) 方法不适用于参数 (String, B)
and
和
The method put(String, capture#1-of ? extends A) in the type Map is not applicable for the arguments (String, C)
类型 Map 中的 put(String, capture#1-of ? extends A) 方法不适用于参数 (String, C)
采纳答案by Trein
Just change the type of the HashMap
to <String, A>
只需将类型更改HashMap
为<String, A>
Map<String, A> map = new HashMap<String, A>();