You can't add anything (other than literal null
) to a Map<String, ?>
, because it could be the wrong type. For example:
Map<String, Long> longMap = ...;
Map<String, ?> wildcardMap = longMap;
wildcardMap.put("", ""); // Compiler error!
// but if it did work, the following would be a runtime error:
Long value = longMap.values().iterator().next();
Remember that ?
is a shorthand for ? extends Object
; and the acronym PECS tells you that something which extends
is a producer, not a consumer. So, you can't invoke a consumer method on an instance of it (unless you pass null
).
If you want to put heterogeneous values into the map, the value type has to be a common superclass of the types.
Map<String, Object> mapForBoth = ...
mapForBoth.put("key1", "string");
mapForBoth.put("key2", 1);
(Actually, Serializable
is a more specific common superclass of String
and Integer
; it's up to you as to whether that's a better value type)