[英]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>
. 编译器说它
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?
为什么?
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
). 原因是Java Generics没有对立/协方差(
HashMap<List>
不是HashMap<ArrayList>
的超类型,尽管List
当然是ArrayList
的超类型)。
This is because a Map<ArrayList>
is not a Map<List>
, even though ArrayList
is a List
. 这是因为
Map<ArrayList>
不是 Map<List>
,即使ArrayList
是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.
以下是我之前对类似问题的回答 ,其中更详细地解释了背后的原因。
试试:
private Map<? extends List<K>, V> multiMap= new HashMap<ArrayList<K>,V>();
BTW: If you want a Multimap, I am pretty sure you want a Map<K, List<V>>
and not a Map<List<K>>, V>
. 顺便说一句:如果你想要一个Multimap,我很确定你想要
Map<K, List<V>>
而不是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. 列表制作了可怜的哈希键,我想不出任何使用List作为键和单个Object作为值有意义的用法。 You should re-think your design.
你应该重新考虑你的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.