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 generics . 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 T , where T is a type parameter. You can then
use this class with the class String plugged in for T to automatically get a class for a list
of String objects. Similarly, you can plug in the class Double for T to obtain a class
for a list of Double s, and you can do a comparable thing for any other class. The class
ArrayList in the standard Java libraries is, in fact, just such a class for a list of items
of type T , where T is a type parameter. We will first show you how to use classes with a
type parameter by using the ArrayList class as an example. We will then tell you how
you can define other classes with a type parameter.
generics
Prerequisites
Section 14.1 covering the ArrayList 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 Tip section entitled “Generic Interfaces” that requires Section 13.1 on
interfaces, but that Tip section can easily be skipped if you have not yet read Section 13.1.)
You need not read Section 14.1 before Section 14.2, but you are encouraged to do so;
Section 14.1 can serve as a motivation for Section 14.2 .
 
Search WWH ::




Custom Search