使用Java泛型与HashMap [英] Using Java Generics with HashMap

查看:655
本文介绍了使用Java泛型与HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个B类和C类,它们都扩展了A类:

  public class B extends A {...} 
public class C extends A {...}

如何使用Java泛型这样一个HashMap?

  B b = new B(); 
C c = new C();

地图< String,?延伸A> map = new HashMap< String,A>();

map.put(B,b);
map.put(C,c);

Eclipse始终显示错误:



Map类型的方法put(String,capture#1-of?extends A)不适用于
参数(String,B)



方法put(String,capture#1 -of?extends A)在类型
中映射不适用于
参数(String,C)


HashMap 的类型更改为< String,A>

 地图< String,A> map = new HashMap< String,A>(); 


I have a class B and C which both extends class A:

public class B extends A {...}
public class C extends A {...}

How can I use Java generics with a HashMap this way?

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:

The method put(String, capture#1-of ? extends A) in the type Map is not applicable for the arguments (String, B)

and

The method put(String, capture#1-of ? extends A) in the type Map is not applicable for the arguments (String, C)

解决方案

Just change the type of the HashMap to <String, A>

Map<String, A> map = new HashMap<String, A>();

这篇关于使用Java泛型与HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆