In the Java collection map <Key,?> What is a "?" To refer to?
In Java collections, I saw something like this: Map<Key,?> . I do not know how this works, can someone help me with this or give an example?
The question mark (?) Represents an unknown type.
In your example, Map<Key, ?> This means that it will correspond to a map containing values โโof any type. It does not mean that you can create a Map<Key, ?> And insert values โโof any type into it.
Quote from the documentation :
In general code, a question mark (?), Called a wildcard, represents an unknown type. You can use a wildcard in various situations: as the type of a parameter, field, or local variable; sometimes as a return type (although better programming practice is more specific). A wildcard is never used as a type argument for a generic method call, an instance of a generic class, or a supertype.
For example, suppose you want to create a function that will print the values โโof any map, regardless of the types of values:
static void printMapValues(Map<String, ?> myMap) { for (Object value : myMap.values()) { System.out.print(value + " "); } } Then call this function by passing the argument Map<String, Integer> as an argument:
Map<String, Integer> myIntMap = new HashMap<>(); myIntMap.put("a", 1); myIntMap.put("b", 2); printMapValues(myIntMap); And you will get:
1 2 The wildcard allows you to call the same function by passing Map<String, String> or any other type of value as an argument:
Map<String, String> myStrMap = new HashMap<>(); myStrMap.put("a", "one"); myStrMap.put("b", "two"); printMapValues(myStrMap); Result:
one two This wildcard is called unlimited because it does not provide type information. There are several scenarios in which you can use an unlimited template:
- If you call methods other than those defined in the
Objectclass. - When you use methods that are independent of the type parameter, such as
Map.size()orList.clear().
The wildcard can be unlimited, bounded above or bounded below:
List<?>Is an example of an unlimited template . It presents a list of elements of an unknown type.List<? extends Number>List<? extends Number>is an example of an upper bounded pattern . It corresponds to aListtypeNumber, as well as its subtypes, such asIntegerorDouble.List<? super Integer>List<? super Integer>is an example of a restricted wildcard . It corresponds to aListtypeInteger, as well as its supertypesNumberandObject.
Unknown wildcard
? can be any data type
List<?> Means a list typed by an unknown type. It can be a list, list, list, etc.
Now going to your example Map<Key,?> Means Value , which should be inserted into this map, can be any data type.