Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
In the Java API, you might see type argument notation that uses a question mark, like this method from theCollections
class:The question mark is called the wildcard type. A wildcard represents some type, but one that is not known at compile time. In this case, it means that thereverse(List<?> list)
reverse
method can accept aList
of any type. It might be aList
ofInteger
, for example, or ofString
.You might think that
List<?>
is the same asList<Object>
. It is not. If thereverse
method had been defined as accepting typeList<Object>
then the compiler would not allow aList<Integer>
, for example, to be passed to the method. When the method is defined withList<?>
you can pass aList<Integer>
, aList<String>
, or a list of any type and they all work.
It is also possible to constrain the wildcard type with an upper or lower bound (but not both). To illustrate how to define a bound, look at the following classes from the JDK API:Hierarchy of some of the
Number
classes.[PENDING: This quick and dirty oversized graphic will be replaced by a polished one from the art department.]
As the figure shows,
Object
is a supertype ofNumber
, which is a supertype ofInteger
,Long
andFloat
(to name three ofNumber
's subtypes).Here is the syntax for constraining a wildcard type with a bound:
super className
The type is constrained with a lower bound. In the case of "List<? super Number
>" theList
must contain eitherNumber
s orObject
s.
extends className
The type is constrained with an upper bound. In the case of "List<? extends Number
>" theList
must containNumber
s,Integer
s,Long
s,Float
s or one of the other subtypes ofNumber
.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.