Java Reference
In-Depth Information
Example 4.5.1-1. Wildcards
Click here to view code image
import java.util.Collection;
import java.util.ArrayList;
class Test {
static void printCollection(Collection<?> c) {
// a wildcard collection
for (Object o : c) {
System.out.println(o);
}
}
public static void main(String[] args) {
Collection<String> cs = new ArrayList<String>();
cs.add("hello");
cs.add("world");
printCollection(cs);
}
}
Note that using Collection<Object> as the type of the incoming parameter, c , would not
be nearly as useful; the method could only be used with an argument expression that
had type Collection<Object> , which would be quite rare. In contrast, the use of an un-
bounded wildcard allows any kind of collection to be used as a parameter.
Here is an example where the element type of an array is parameterized by a wildcard:
public Method getMethod(Class<?>[] parameterTypes) { ... }
Wildcards may be given explicit bounds, just like regular type variable declarations. An
upper bound is signified by the following syntax, where B is the bound:
? extends B
Unlike ordinary type variables declared in a method signature, no type inference is required
when using a wildcard. Consequently, it is permissible to declare lower bounds on a wild-
card, using the following syntax, where B is a lower bound:
? super B
Example 4.5.1-2. Bounded Wildcards
boolean addAll(Collection<? extends E> c)
Search WWH ::




Custom Search