|
|
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 theCollectionsclass: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)reversemethod can accept aListof any type. It might be aListofInteger, for example, or ofString.You might think that
List<?>is the same asList<Object>. It is not. If thereversemethod 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
Numberclasses.[PENDING: This quick and dirty oversized graphic will be replaced by a polished one from the art department.]
As the figure shows,
Objectis a supertype of
Number, which is a supertype of
Integer,
Longand
Float(to name three of
Number'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>" theListmust contain eitherNumbers orObjects.
extends className
The type is constrained with an upper bound. In the case of "List<? extends Number>" theListmust containNumbers,Integers,Longs,Floats 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.