Map <String, Map <String, Boolean >> myMap = new HashMap <String, HashMap <String, Boolean >> ();
Why it does not work in java, but it does
Map<String, Map<String, Boolean>> myMap = new HashMap<String,Map<String,Boolean>>(); Just to make it clear that the change to the nested HashMap below shows a compiler error, while the above does not; with map (not hashmap)
Map<String, Map<String, Boolean>> myMap = new HashMap<String,HashMap<String,Boolean>>(); +4
3 answers
This is due to the fact that generics in Java are invariant, i.e. even if class B is A, a Collection<B> not Collection<A> .
And this is for a good reason. If your example was 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! +9
In the second case, myMap is a map whose keys are of type String , and values are of type Map<String, Boolean> . HashMap<String, Boolean> 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>>(); +5