Java Reference
In-Depth Information
11.4. Wildcard Capture
Wildcards represent an unknown type, but whenever a variable that has
a wildcard type is used, the compiler must treat it as having some spe-
cific type so that it can check for correct usage. This specific (but still un-
known) type is referred to as the capture of the wildcard. The place you
will most commonly come across the capture of a wildcard is in the error
messages the compiler produces when you use a parameterized type the
wrong way. For example, recall the incorrect attempt to add a String ob-
ject to a queue accessed through an unbounded wildcard reference:
SingleLinkQueue<?> strings =
new SingleLinkQueue<String>();
strings.add("Hello"); // INVALID: won't compile
The error message this produced from the compiler we used was:
add(capture of ?) in SingleLinkQueue<capture of ?> cannot be
applied to (java.lang.String)
This is telling us that when the wildcard reference strings is used, the
type of queue is SingleLinkQueue<captureof ?> , so the type of the para-
meter to add is also " captureof ? ". Because String is not compatible with
" captureof ? " the call is not allowed. Even if the wildcard is bounded, as
in the earlier example with the queue of numbers (" ?extends Number " ) , the
type of the parameter to add is " captureof ?extends Number " which is still
not compatible with Integer , even though Integer is a subtype of Number .
If a wildcard is always represented by its capture, it would seem that
once you have a wildcard type you can only use it wherever a wildcard
type is expected. Indeed this is a basic rule that ensures the integrity of
the type system.
 
Search WWH ::




Custom Search