使用泛型的HashMap [英] HashMap using Generics
问题描述
我有:
受保护的地图< 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
和泛型
。
你需要一个普通的交易集合
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 Transaction
s:
protected Map<String, Transaction> transactions = new HashMap<String, Transaction>();
这篇关于使用泛型的HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!