HashMap using Generics

2019-09-09 08:24发布

问题:

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?

回答1:

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


回答2:

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.