开发者

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

开发者 https://www.devze.com 2023-04-03 04:39 出处:网络
What is wrong with 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 clas开发者_如何学Gos of List? Why?


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


Try :

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消