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

微笑、不失礼 提交于 2019-12-05 13:00:39

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!

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

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

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