The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Wildcard Types

In the Java API, you might see type argument notation that uses a question mark, like this method from the Collections class:
reverse(List<?> list) (in the API reference documentation)
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 the reverse method can accept a List of any type. It might be a List of Integer, for example, or of String.

You might think that List<?> is the same as List<Object>. It is not. If the reverse method had been defined as accepting type List<Object> then the compiler would not allow a List<Integer>, for example, to be passed to the method. When the method is defined with List<?> you can pass a List<Integer>, a List<String>, or a list of any type and they all work.

Constraining a Type with a Bound

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:

The following paragraph describes this figure.

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 (in the API reference documentation) is a supertype of Number (in the API reference documentation), which is a supertype of Integer (in the API reference documentation), Long (in the API reference documentation) and Float (in the API reference documentation) (to name three of Number's subtypes).

Here is the syntax for constraining a wildcard type with a bound:


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.