Map< String,Map< String,Boolean>> myMap = new HashMap< String,HashMap< String,Boolean>>(); [英] Map<String, Map<String, Boolean>> myMap = new HashMap<String,HashMap<String,Boolean>>();

查看:275
本文介绍了Map< String,Map< String,Boolean>> myMap = new HashMap< String,HashMap< String,Boolean>>();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不在java中工作,但是这样做

Why doesn't that work in java, but this does

Map<String, Map<String, Boolean>> myMap = new HashMap<String,Map<String,Boolean>>();

为了澄清嵌套HashMap的下面的变化,显示了一个编译器错误,而上面没有; (不是hashmap)

Just to clarify the below alteration of the nested HashMap shows a compiler error, whereas the above does not not; with a Map (not hashmap)

Map<String, Map<String, Boolean>> myMap = new HashMap<String,HashMap<String,Boolean>>();


推荐答案

这是因为Java中的泛型是不变的即使B类是A, Collection 不是 a Collection A>

This is because generics in Java are invariant, i.e. even if class B is an A, a Collection<B> is not a Collection<A>.

这是一个很好的理由。如果您的示例合法,则可以这样做:

And this is for a good reason. If your example were legal, this would be possible:

Map<String, HashMap<String, Boolean>> myHashMap = new HashMap<String,HashMap<String,Boolean>>();
Map<String, Map<String, Boolean>> myMap = myHashMap;
myMap.put("oops", new TreeMap<String, Boolean>());
HashMap<String, Boolean> aHashMap = myMap.get("oops"); // oops - ClassCastException!

这篇关于Map&lt; String,Map&lt; String,Boolean&gt;&gt; myMap = new HashMap&lt; String,HashMap&lt; String,Boolean&gt;&gt;();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆