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

南楼画角 提交于 2020-01-23 08:36:05

问题


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

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

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>>();

回答1:


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!



回答2:


In the second case myMap is a map which keys are of type String and values are of type Map<String, Boolean>. HashMap<String, Boolean> is not a Map<String, Boolean> it implements it. Therefore, this will compile:

Map<String, ? extends Map<String, Boolean>> myOtherMap = 
    new HashMap<String,HashMap<String,Boolean>>();



回答3:


I think that's because of the difference between Map<String, Boolean> and HashMap<String,Boolean>. Indeed, the generics are here a specification, which must be the same on both sides. (or at least that's my opinion).



来源:https://stackoverflow.com/questions/3636834/mapstring-mapstring-boolean-mymap-new-hashmapstring-hashmapstring-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!