Meaning of ? in Map<String, ?>

11,143

Solution 1

In Java generics the ? stands for wildcard, which represent any object.

If you create a method that takes Map<String, ?> you are saying that you expect a Map that maps from String keys to any possible object values:

public static void main(String[] args) {
    Map<String, Object> map1 = null;
    Map<String, String> map2 = null;

    test(map1);
    test(map2);
}

private static void test(Map<String, ?> settings) {}

Solution 2

I had difficulties when I need to pass Map<String, ?> to my function, which was accepting Map<String, Object>. And this cut it:

Map<String, ?> mapQuestion = ...
mapObject = (Map<String, Object>)mapQuestion;
Share:
11,143
Alpha
Author by

Alpha

Updated on June 11, 2022

Comments

  • Alpha
    Alpha almost 2 years

    Method createBuilderFactory in javax.json needs argument of type Map<String, ?>

    Generally, we have map with like Map<String, String>(some other data types in place of String)

    But I didn't understand what does ? stands for. And in order to pass argument of type Map<String, ?>, how I should define the map.

    Can someone please help me to understand this better?