Java Reference
In-Depth Information
This conversion of the capture of the wildcard to the type
T
is known as
capture conversion
and it complements the other type conversions that
we discussed in
Section 9.4
on page
216
.
For capture conversion to apply, there must be a unique mapping
between the capture of the wildcard and the type variable involved. This
leads to some general restrictions on when capture conversion can ap-
ply.
First, capture conversion won't apply if the type parameter is used
with more than one method parameter. Consider a utility method that
merges two lists:
static <T> List<T> merge(List<T> first, List<T> second) {
/* ... */
}
If you try to pass an argument of type
List<?>
for
first
and
second
it will
faileven if you passed the same reference. The problem is that the pro-
cess for resolving the method call will essentially replace the type of the
first argument with
X
, the type of the second argument with
Y
, and then
see if
T
is uniquely determined. But because
X
is not the same as
Y
this
will not be the case.
Second, you can only apply capture conversion if the type variable is
defined at the top-level of the generic type. For example, suppose you
had the method
static <T> void processListOfLists(List<List<T>> list) {
/* ... */
}
and you tried to invoke it with an argument of type
List<List<?>>
. The
capture of the wildcard would not uniquely determine an element type
for the outer
List
. The method requires a
List
with elements that are all