Java Reference
In-Depth Information
14
Generics and the
ArrayList
Class
Hamlet: Do you see yonder cloud that's almost in shape of a camel?
Polonius: By the mass, and 'tis like a camel, indeed.
Hamlet: Me think it is like a weasel.
Polonius: It is backed like a weasel.
Hamlet: Or like a whale.
Polonius: Very like a whale.
WILLIAM SHAKESPEARE,
Hamlet
Introduction
Beginning with version 5.0, Java allows class and method definitions that include
parameters for types. Such definitions are called
. Generic programming with
a type parameter allows you to write code that applies to any class. For example, you
can define a class for a list of items of type
generics
generics
, where
is a type parameter. You can then
T
T
use this class with the class
plugged in for
to automatically get a class for a list of
String
T
objects. Similarly, you can plug in the class
for
to obtain a class for a list
String
Double
T
of
s, and you can do a similar thing for any other class. The class
in the
Double
ArrayList
standard Java libraries is, in fact, just such a class for a list of items of type
is
a type parameter. We will first show you how to use classes with a type parameter by
using the
, where
T
T
class as an example. We will then tell you how you can define
other classes with a type parameter.
ArrayList
Prerequisites
class requires only Chapters 1 through 6 and
Chapter 9. It can reasonably be read without first reading Chapter 9 if you ignore all
references to “exceptions.”
Section 14.2 on generics requires Chapters 1 through 7 and Chapter 9. (There is
one very short Pitfall section entitled “Generic Interfaces” that requires Section 13.1
on interfaces, but that Pitfall section can easily be skipped if you have not yet read Sec-
tion 13.1.) You need not read Section 14.1 before Section 14.2, but you are encour-
aged to do so; Section 14.1 can serve as a motivation for Section 14.2.
Section 14.1 covering the
ArrayList
Search WWH ::




Custom Search