使用泛型的HashMap [英] HashMap using Generics

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

问题描述

我有:

 受保护的地图< String,?延伸交易> transactions = new HashMap< String,?>(); 

但是,我收到一个编译错误:

 类型不匹配:无法从HashMap转换< String,?>映射< String,?延伸交易> 

我试过一些变化,包括:

 受保护的地图< String,?延伸交易> transactions = new HashMap< String,?扩展Transaction>(); 

所有产生相同的编译错误。

我的目标是让一个报表 抽象类的实例(由许多不同类型的报表扩展),接受多个抽象类 事务的子范围。

进入扩展 Report 的单个实例的类型将全部为相同类型,例如 TRRReport extends Report 将需要接受 TRRTransaction扩展Transaction 到它的 HashMap ,但是 TDDReport extends Report 需要接受 TDDTransaction extends Transaction 到它的 HashMap HashMap 泛型

c $ c>在这种情况下?

解决方案

在通用参数中是当你想在变量中存储一个未知类型的集合。这就是所谓的协变。



你需要一个普通的交易集合 s:

 受保护的地图< String,Transaction> transactions = new HashMap< String,Transaction>(); 


I have:

protected Map<String, ? extends Transaction> transactions = new HashMap<String, ?>();

However, I get a compilation error:

Type mismatch: cannot convert from HashMap<String,?> to Map<String,? extends Transaction>

I've tried some variations, including:

protected Map<String, ? extends Transaction> transactions = new HashMap<String, ? extends Transaction>();

All yield the same compilation error.

My goal is to have an instance of Report abstract class (extended by many different kinds of reports), accept multiple subclassess of the abstract class Transaction.

The types going into a single instance of an extended Report will all be the same type, for example TRRReport extends Report will need to accept TRRTransaction extends Transaction into it's HashMap, however TDDReport extends Report will need to accept TDDTransaction extends Transaction into it's HashMap.

How can I use a HashMap and Generics in this situation?

解决方案

The point of ? in generic parameters is when you want to store a collection of an unknown type in a variable. This is called covariance.

You want a regular generic collection of Transactions:

protected Map<String, Transaction> transactions = new HashMap<String, Transaction>();

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

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