Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add values for java generic map with undetermined "?" value type

I've seen this kind of declaration in jdk 8 sample:

    Map<String, ?> map = new HashMap<>(3);//OK

But when I tried to add value to "map", I didn't succeed:

    map.put("abc", Optional.of(5));
    map.put("kk", "xyz");

Both fail to compile. I wish to know:

(1) What does "?" indicate in Map declaration above?

(2) How to give values to this "map"?

like image 206
Hind Forsum Avatar asked Nov 30 '22 21:11

Hind Forsum


1 Answers

Map<String,?> is an abstract type. If a variable has this type, it could reference an object with any of the following types (and others).

  • HashMap<String,Integer>
  • TreeMap<String,String>
  • HashMap<String,ArrayList<Boolean>>
  • TreeMap<String,Throwable>

Obviously, the possibilities are basically endless. If you have a variable of this type, you know that it refers to a map whose keys are String, but you really know nothing else. In particular, you don't know what type of object you'll end up with when you do a get on that Map.

More importantly though, you will never be able to put anything into the map, without some kind of nasty, unsafe casting operation. The compiler will stop you. So in the examples you've given -

  • map.put("abc", Optional.of(5)); won't compile, because map could be a HashMap<String,String>, into which you can't put an Optional.
  • map.put("kk", "xyz"); won't compile, because map could be a TreeMap<String,Integer>, into which you can't put a String.

The exceptions would be null, or any value that has come from the map itself - see Andy Turner's excellent answer for more detail about those possibilities.

In short, if you have a variable of type Map<String,?>, the operations that the compiler will let you do to it are a bit limited. You can't put anything into the map, unless it's null or it's already in the map. All you can do is get values from the map, and remove values from the map.

So using a Map<String,?> variable is very limiting. If all you want to do with the map is read values from it, this is just fine, of course. But don't expect to be able to insert arbitrary values into the map, unless you use a different expression to refer to the map.

like image 72
Dawood ibn Kareem Avatar answered Dec 04 '22 03:12

Dawood ibn Kareem