简体   繁体   中英

HashMap using Generics

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>();

Instead of initializing it with

new HashMap<String, ?>();

You can use diamond inference:

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

In that case the javacompiler will find out what to write at the constructor side itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM