3

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?

Philipp Wendler
  • 11,184
  • 7
  • 52
  • 87
Numerator
  • 1,389
  • 3
  • 21
  • 40
  • 2
    Generics is more pedantic than regular Java casts. You cannot up cast a generic like you can with a regular expression. – Peter Lawrey Sep 05 '11 at 09:09
  • Where the answers helpful? If so please accept one of them. If not, you can provide further details to help people answering the question. – Philipp Wendler Sep 15 '11 at 08:18

4 Answers4

14

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).

Philipp Wendler
  • 11,184
  • 7
  • 52
  • 87
2

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.

Community
  • 1
  • 1
Péter Török
  • 114,404
  • 31
  • 268
  • 329
2

Try :

private Map<? extends List<K>, V> multiMap= new HashMap<ArrayList<K>,V>();
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
2

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.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588