Java Reference
In-Depth Information
Wildcards
Classes and interfaces in the collection framework use some parameter type
specifications that we have not seen before. For example, they allow you to say things
such as, “The argument must be a
ArrayList<T>
but it can have any base type.” More
generally these new parameter type specifications use generic classes but do not fully
specify the type plugged in for the type parameter. Because they specify a wide range of
argument types, they are known as
wildcards
.
The easiest wildcard to understand is
<?>
, which says that you can use any type in
place of the type parameter. For example,
wildcard<
?
>
public void
sampleMethod(String arg1, ArrayList<?> arg2)
is invoked with two arguments. The first argument must be of type
String
. The
second argument can be a
ArrayList<T>
with any base type.
Note that
ArrayList<?>
is different from
ArrayList<Object>
. For example, if
the type specification is
ArrayList<?>
, then you can plug in an argument of type
ArrayList<String>
(as well as other types); you cannot plug in an argument of type
ArrayList<String>
if the type specification is
ArrayList<Object>
.
You can place a bound on a wildcard saying the type used in place of the wildcard
must be an ancestor type or a descendent type of some class or interface. For example,
<? extends String>
says that the argument plugged in can be an object of any
descendent class of the class
String
. The notation, restrictions, and meaning are the
same as what we described for type bounds such as
<T extends String>
, which we
discussed in Chapter 14 .
For example,
extends
public void
anotherMethod(String arg1, ArrayList<?
extends
String> arg2)
is invoked with two arguments. The first argument must be of type
String
, but the
second argument can be of any
ArrayList<T>
object provided the base type of the
ArrayList<T>
is a descendent type of
String
.
To specify that the wildcard type be an ancestor type of some class or interface, use
super
rather than
extends
. For example,
ArrayList<? super String>
specifies
an
ArrayList<T>
whose base type can be any ancestor class of the class
String
. As it
turns out, we will have no occasion to use wildcard types involving
super
.
super
The Collection Framework
The
Collection<T>
interface is the highest level of Java's framework for collection
classes. This interface describes the basic operations that all collection classes should
implement. A summary of these operations (method headings) for the
Collection<T>
interface are given in Display 16.2. A more complete description can be found in
Appendix 5. Because an interface is a type, you can define methods with a parameter
of type
Collection<T>
. That parameter can be filled in with an argument that is an
object of any class in the collection framework (that is, any class that implements the
Collection<T>
interface