13

In Java Collections I saw something like this: Map<Key,?>. I don't know how it is working, can anyone help me out with this or provide an example?

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Gowtham Murugesan
  • 407
  • 2
  • 6
  • 17

2 Answers2

30

The question mark (?) represents an unknown type.

In your example, Map<Key, ?>, it means that it will match a map containing values of any type. It does not mean you can create a Map<Key, ?> and insert values of any type in it.

Quoting from the documentation:

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

For example, say you want to create a function that will print the values of any map, regardless of the value types:

static void printMapValues(Map<String, ?> myMap) {
    for (Object value : myMap.values()) {
        System.out.print(value + " ");
    }
}

Then call this function passing a Map<String, Integer> as argument:

Map<String, Integer> myIntMap = new HashMap<>();
myIntMap.put("a", 1);
myIntMap.put("b", 2);
printMapValues(myIntMap);

And you would get:

1 2

The wildcard allows you to call the same function passing a Map<String, String>, or any other value type, as argument:

Map<String, String> myStrMap = new HashMap<>();
myStrMap.put("a", "one");
myStrMap.put("b", "two");
printMapValues(myStrMap);

Result:

one two

This wildcard is called unbounded, since it gives no information about the type. There are a couple of scenarios where you may want to use the unbounded wildcard:

  • If you're calling no methods except those defined in the Object class.
  • When you're using methods that don't depend on the the type parameter, such as Map.size() or List.clear().

A wildcard can be unbounded, upper bounded, or lower bounded:

  • List<?> is an example of an unbounded wildcard. It represents a list of elements of unknown type.

  • List<? extends Number> is an example of an upper bounded wildcard. It matches a List of type Number, as well as its subtypes, such as Integer or Double.

  • List<? super Integer> is an example of a lower bounded wildcard. It matches a List of type Integer, as well as its supertypes, Number and Object.

Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
1

The Unknown Wildcard

? can be any dataType

List<?> means a list typed to an unknown type , This could be a List<Integer>, a List<Boolean>, a List<String> etc.

Now coming to your example Map<Key,?> means Value which is to be inserted in this map can be of any data Type.

Tetrinity
  • 1,105
  • 8
  • 20
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62