繁体   English   中英

私人地图 <List<K> ,V&gt; multiMap = new HashMap <ArrayList<K> ,V&gt;();

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

出什么问题了

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

编译器说它Type mismatch: cannot convert from HashMap<ArrayList<K>,V> to Map<List<K>,V> 我是否必须提供特定类别的列表? 为什么?

你必须写

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

通用参数的值必须在两侧完全匹配(只要您不使用通配符)。 原因是Java Generics没有对立/协方差( HashMap<List>不是HashMap<ArrayList>的超类型,尽管List当然是ArrayList的超类型)。

这是因为Map<ArrayList> 不是 Map<List> ,即使ArrayListList 虽然这听起来有点违反直觉,但这是有充分理由的。 以下是我之前对类似问题的回答 ,其中更详细地解释了背后的原因。

试试:

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

顺便说一句:如果你想要一个Multimap,我很确定你想要Map<K, List<V>>而不是Map<List<K>>, V> 列表制作了可怜的哈希键,我想不出任何使用List作为键和单个Object作为值有意义的用法。 你应该重新考虑你的设计。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM