Java Reference
In-Depth Information
In this example, the wildcard indicates that we require a
List
of any
type, as long as that type is
Number
or a subclass of
Number
. More formally,
we've used a
bounded wildcard,
where
Number
forms the upper bound on
the type that is expected: Whatever type we get, it must be at least a
Number
.
You can also specify that a wildcard type must be the same as, or a
supertype of, another. You do this by using the keyword
super
rather
than
extends
. For example, you could use
List<?super Integer>
to match
a
List
of
Integer
or any of its supertypes:
List<Integer>
,
List<Number>
,
List<Serializable>
,
List<Comparable<Integer>>
, or
List<Object>
. In this
case the type represents the
lower bound
on the wildcard's type.
Note that unlike a bounded type variable, a bounded wildcard can have
only a single boundeither an upper bound or a lower bound. For ex-
ample, if you would like to restrict the type of list to be one containing
elements that are at least of class
Value
and also implement
Serializ-
able
, you cannot say
List<?extends Value& Serializable>
.
Of course, you can also have an
unbounded wildcard.
For example,
List<?>
represents a list of any kindimplicitly the upper bound is
Object
.
But remember that
List<?>
is not another way of saying
List<Object>
;
rather, it is a way of saying
List<?extends Object>
.
In contrast to the non-wildcard versions, parameterized types that in-
clude a bounded wildcard are related in the way you might have ex-
pected. For example,
List<?extends Integer>
is a subtype of
List<?extends
Number>
, which is itself a subtype of
List<?>
. Similarly,
List<?super Number>
is a subtype of
List<?super Integer>
. In addition, non-wildcard paramet-
erized types are subtypes of suitably bounded, wildcard parameterized
types. For example,
List<Number>
is a subtype of
List<?extends Number>
, as
is
List<Integer>
. While this in itself is a good property to have, the differ-
ence between the behavior with and without bounded wildcards can be
a source of confusion. Perhaps the following diagram will clarify things: