Java Reference
In-Depth Information
Parameterized Classes and Generics
The class ArrayList is a parameterized class . It has a parameter, which we have been
denoting Base_Type , that can be replaced by any reference type to obtain a class for
ArrayList s with the specified base type. ArrayList is just a class that somebody
defined (and placed in the standard Java library package java.util ), so you should
also be able to define these kinds of classes. Starting with version 5.0, Java allows class
definitions with parameters for types. These classes that have type parameters are
called parameterized class or generic definitions or, more simply, generics . You
already know how to use classes with a type parameter, because we have been using the
parameterized class ArrayList . In Section 14.2, we will show you how to write your
own parameterized classes.
parameterized
class
generics
PITFALL: Nonparameterized ArrayList and Vector Classes
The ArrayList and Vector classes we discussed in this section have a type parameter
for the base type. There are also ArrayList and Vector classes with no parameter for
the base type. (They have base type Object .) These ArrayList and Vector classes
without type parameters are left over from earlier versions of Java. When checking
details in the Java documentation, be sure you get the documentation for the Array-
List and Vector classes that have a type parameter. Using notation we introduce in
Section 14.2, the versions with type parameters are usually written as ArrayList<E>
and Vector<E> or as ArrayList<T> and Vector<T> in the Java documentation.
14.2
Generics
You can have this dish prepared with any type of meat or fish.
Entry on a restaurant menu
Starting with version 5.0, Java allows class definitions that contain a parameter (or
parameters) for a type (or types). In this section, we teach you how to write class defi-
nitions that contain a type parameter.
Generic Basics
Classes and methods can have a type parameter. The type parameter may then have
any reference type, and hence any class type, plugged in for the type parameter. This
plugging in produces a specific class type or method. For example, Display 14.4 shows
a very simple class definition with a type parameter T . You may use any nonkeyword
identifier for the type parameter; you need not use T . However, by convention, type
type parameter
Search WWH ::




Custom Search