This statement is not working
Map<String, HashMap<String, Object>> customs = new LinkedHashMap<String, CustomHashMap>();
because customs
is of type Map<String, HashMap<String, Object>>
and you are assigning a LinkedHashMap
which is of type <String, CustomHashMap>
, where CustomHashMap
is a sub class of HashMap<String, Object>
.
Generics are invariant
: for any two distinct types T1
and T2
, HashMap<String, T1>
is neither a subtype nor a supertype of HashMap<String, T2>
. So, LinkedHashMap<String, CustomHashMap>
cannot be assigned to Map<String, HashMap<String, Object>>
. On the other hand, arrays are covariant
, which means below statement will compile without any error or warning. But, it might fail at run time (which might cause more harm) if you put any other subtype of HashMap<String, Object>
into it other than CustomHashMap
:
HashMap<String, Object>[] mapArray = new CustomHashMap[1];
mapArray[0] = new CustomHashMap_1();// this will throw java.lang.ArrayStoreException
Now, if you want to assign LinkedHashMap<String, CustomHashMap>
to Map<String, HashMap<String, Object>>
, change the statement to this:
Map<String, ? extends HashMap<String, Object>> customs = new LinkedHashMap<String, CustomHashMap>();
Some additional information about this approach is nicely explained by @Seelenvirtuose , which is the accepted answer.