Java Reference
In-Depth Information
interface, we need a brief detour to learn a bit
more about parameter type specifications.
Before we discuss the
Collection<T>
Wildcards
Classes and interfaces in the collection framework use some parameter type specifica-
tions that we have not seen before. For example, they allow you to say things such as,
“The argument must be a
but it can have any base type.” More gener-
ally 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 argu-
ment types, they are known as
ArrayList<T>
wildcards
.
wildcard <?>
The easiest wildcard to understand is
, which says that you can use any type in
<?>
place of the type parameter. For example,
public void sampleMethod(String arg1, ArrayList<?> arg2)
is invoked with two arguments. The first argument must be of type
. The sec-
String
ond argument can be a
with any base type.
ArrayList<T>
Note that
is different from
. For example, if the
ArrayList<?>
ArrayList<Object>
type specification is
, then you can plug in an argument of type
ArrayList<?>
(as well as other types); you cannot plug in an argument of type
ArrayList<String>
.
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,
if the type specification is
ArrayList<String>
ArrayList<Object>
says that the argument plugged in can be an object of any descendent
extends
<? extends String>
class of the class
. The notation, restrictions, and meaning are the same as what we
described for type bounds such as
String
, which we discussed in Chapter 14.
<T extends String>
For example,
public void
anotherMethod(String arg1, ArrayList<? extends String> arg2)
is invoked with two arguments. The first argument must be of type
, but the
String
second argument can be of any
object provided the base type of the
ArrayList<T>
.
To specify that the wildcard type be an ancestor type of some class or interface, you
use super rather than extends. For example,
is a descendent type of
ArrayList<T>
String
specifies an
super
ArrayList<? super String>
whose base type can be any ancestor class of the class
. As it turns
ArrayList<T>
String
out, we will have no occasion to use wildcard types involving
.
super
The Collection Framework
The
interface is the highest level of Java's framework for collection
Collection<T>
classes. The
interface describes the basic operations that all collection
Collection<T>
Search WWH ::




Custom Search