In Java Collections Map<Key,?> What does "?" refer to?
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()
orList.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 aList
of typeNumber
, as well as its subtypes, such asInteger
orDouble
.List<? super Integer>
is an example of a lower bounded wildcard. It matches aList
of typeInteger
, as well as its supertypes,Number
andObject
.