Java Reference
In-Depth Information
When a wildcard is used with the
extends
keyword, an upper bound is estab-
lished for the type parameter. In this example,
? extends Number
means any type
that is either a
Number
or a subtype of a
Number
. Therefore, the following would be
valid assignments because both
Integer
and
Double
are subtypes of
Number
:
cList = new LinkedList<Number>();
cList = new LinkedList<Integer>();
cList = new LinkedList<Double>();
So,
cList
can hold a reference to any
List
instance that has an element type that
is compatible with
Number
. In fact,
cList
could even reference a raw type. Obvi-
ously, this makes it a challenge for the compiler to enforce type safety if it were to al-
low elements to be added to
cList
. Therefore, the compiler does not allow elements
(other than a
null
) to be added to a collection type that is parameterized with
? ex-
tends
. The following would result in a compiler error:
cList.add(new Integer(5)); // add() not allowed; cList
could be LinkedList<Double>
However, you are allowed to get an element from the list without any problem:
Number cNum = cList.get(0);
The only restriction here is that the reference you get from the list has to be treated
like a
Number
. Remember,
cList
could be pointing to a list of
Integers
, a list of
Doubles
, or list of any other subtype of
Number
.
A wildcard can also be used with the
super
keyword. In this case, a lower bound
is established for the type parameter:
List<? super Integer> dList;
In this example,
? super Integer
means any type that is either an
Integer
or any supertype of
Integer
. Therefore, the following would be valid assignments
because
Number
and
Object
are the only supertypes of
Integer
: