Java Reference
In-Depth Information
Generic Wildcards
A wildcard generic type is an unknown generic represented with a question mark, ? . The
wildcard provides a polymorphic-like behavior for declaring generics. You can use generic
wildcards in three ways:
? , an unbounded wildcard
? extends type , a wildcard with an upper bound
? super type , a wildcard with a lower bound
This section examines each of these wildcard uses, starting with the unbounded
wildcard.
Unbounded Wildcards
The unbounded wildcard represents any data type, similar to the <T> syntax. Use the ?
in situations where you do not need a formal parameter type like <T> . For example, the
following for-each loop takes in a List of any type. Because the loop does not need to
know the actual data type, it uses a wildcard:
public static void printList(List<?> list) {
for(Object x : list) {
System.out.println(x.toString());
}
}
Any List of any generic type can be passed into the printList method. For example,
the following statements invoke printList with an ArrayList<String> object:
ArrayList<String> keywords = new ArrayList<String>();
keywords.add(“java”);
keywords.add(“generics”);
keywords.add(“collections”);
printList(keywords);
The output of the statements is
java
generics
collections
Upper-Bound Wildcards
As discussed in the sidebar “Understanding Polymorphism and Generics , ” polymorphism is
not quite as apparent with generics. For example, the following statement is valid:
ArrayList<Double> list = new ArrayList<Double>();
Search WWH ::




Custom Search