Java Reference
In-Depth Information
However, as it stands this basic rule imposes a rather annoying restric-
tion. A wildcard represents any type. Similarly, the type variable of a
generic method represents any type. But under the basic rule a wild-
card type can only be used where a wildcard type is expected. This pre-
cludes passing wildcard types to generic methods that have a parameter
defined by a type variable. Consider the
synchronizedList
utility meth-
od from the
Collections
classpart of the
java.util
package discussed in
more detail in
Chapter 21
.
Its job is to take an arbitrary list object and
return a new list object that is backed by the original, but one for which
all the methods are
synchronized
to make access to the list thread-safe
(see
Chapter 14
). The method is declared as follows:
static <T> List<T> synchronizedList(List<T> list) { ... }
There is no logical reason why we should not be able to pass it a list
referenced through a wildcard type:
static void processList(List<?> list) {
List<?> slist = Collections.synchronizedList(list);
// ... process the list
}
To do so is quite safeand quite convenient!
Although in general you cannot use a
List<?>
where a
List<T>
is expected
because the actual type represented by the wildcard is not known to be
compatible with
T
, a special rule bridges the gap that would otherwise
exist between wildcard types and the type variables of generic meth-
ods. This rule allows (under the right circumstances) the capture of the
wildcard to be represented as some unknown generic type
X
and then
to infer in the call that
T
is
X
. You don't actually need to know what
X
iswhatever it is, the resulting use of the list is guaranteed to be type-
safe.