0

How could I add string and int value to a HashMap same time ?

HashMap<String,?> map =new HashMap<>();
map.put("sss", "str");
map.put("sss", 1);

How Android SharedPreferences.getAll() method did this?

Error message

Found 'java.lang.String', required: '?'
luqiang tian
  • 57
  • 1
  • 6

2 Answers2

3

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)

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Try this

 HashMap<String,Object> map =new HashMap<>();
 map.put("sss", "str");
 map.put("sss", 1);
pramesh
  • 1,914
  • 1
  • 19
  • 30