Numerator
Numerator

Reputation: 1409

private Map<List<K>, V> multiMap= new HashMap<ArrayList<K>,V>();

What is wrong with

private Map<List<K>, V> multiMap= new HashMap<ArrayList<K>,V>();

The complier says that it Type mismatch: cannot convert from HashMap<ArrayList<K>,V> to Map<List<K>,V>. Do I have to give a specific class of List? Why?

Upvotes: 3

Views: 2302

Answers (4)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298918

BTW: If you want a Multimap, I am pretty sure you want a Map<K, List<V>> and not a Map<List<K>>, V>. Lists make miserable Hash keys, and I can't think of any usage where it would make sense to use the List as key and a single Object as value. You should re-think your design.

Upvotes: 2

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116266

This is because a Map<ArrayList> is not a Map<List>, even though ArrayList is a List. Although this sounds counterintuitive, there is a good reason for this. Here is a previous answer of mine to a similar question, which explains the reasons behind this in more detail.

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53829

Try :

private Map<? extends List<K>, V> multiMap= new HashMap<ArrayList<K>,V>();

Upvotes: 2

Philipp Wendler
Philipp Wendler

Reputation: 11433

You have to write

private Map<List<K>, V> multiMap= new HashMap<List<K>,V>();

The values of the generic parameters have to match exactly on both sides (as long as you don't use wildcards). The reason is that Java Generics do not have contra-/covariance (HashMap<List> is not a supertype of HashMap<ArrayList>, although List of course is a supertype of ArrayList).

Upvotes: 14

Related Questions