Java Map<String, Map<String, Boolean>> myMap = new HashMap<String,HashMap<String,Boolean>>();
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3636834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Map<String, Map<String, Boolean>> myMap = new HashMap<String,HashMap<String,Boolean>>();
提问by NimChimpsky
Why doesn't that work in java, but this does
为什么这在 java 中不起作用,但这样做
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)
只是为了澄清嵌套 HashMap 的以下更改显示了编译器错误,而以上则没有;带有地图(不是哈希图)
Map<String, Map<String, Boolean>> myMap = new HashMap<String,HashMap<String,Boolean>>();
采纳答案by Péter T?r?k
This is because generics in Java are invariant, i.e. even if class B is an A, a Collection<B>
is nota Collection<A>
.
这是因为在Java泛型是不变的,也就是说,即使B类是A,一个Collection<B>
是不是一个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!
回答by Riduidel
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).
我认为这是因为之间的差异Map<String, Boolean>
和HashMap<String,Boolean>
。事实上,这里的泛型是一个规范,双方必须相同。(或者至少这是我的意见)。
回答by Boris Pavlovi?
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:
在第二种情况下myMap
是一个映射,其中键是 type String
,值是 type Map<String, Boolean>
。HashMap<String, Boolean>
不是Map<String, Boolean>
它实现它。因此,这将编译:
Map<String, ? extends Map<String, Boolean>> myOtherMap =
new HashMap<String,HashMap<String,Boolean>>();