Java Reference
In-Depth Information
16
Collections, Maps and Iterators
Science is built up with facts, as a house is with stones. But a collection
of facts is no more science than a heap of stones is a house.
JULES HENRI POINCARÈ, Quoted by Bertrand Russell in the preface to
Science and Method
Introduction
collection
A
collection
is a data structure for holding elements. For example, an
ArrayList<T>
object is a collection. Java has a repertoire of interfaces and classes that give a uniform
treatment of collections. An
iterator
is an object that cycles through all the elements
in a collection. In this chapter we discuss collections and iterators.
iterator
Prerequisites
Sections 16.1 to 16.3 can be considered one single large topic. These three sections
require Chapters 1 through 9, Section 13.1 of Chapter 13, which covers interfaces,
Chapter 14 on generics and the
class, and Chapter 15 on linked data
structures. The material on inner classes in Chapter 13 (Sections 13.2 and 13.3) is not
needed except for a brief reference in the Programming Tip entitled “Defining Your
Own Iterator Classes,” which requires Section 13.2 (but not 13.3).
None of the material in this chapter is needed for the material on Swing and GUIs.
So, you may skip this chapter and go directly to Chapter 17 if you prefer to cover
Swing GUIs before considering the material of this chapter.
ArrayList<T>
16.1
Collections
Put all your eggs in one basket and
—WATCH THAT BASKET.
MARK TWAIN, Pudd'nhead Wilson
A Java collection is a class that holds objects. This concept is made precise by the
interface. A Java collection is any class that implements the
Collection<T>
Collection<T>
interface. As we shall see, many of these classes can be used as predefined data structures
similar to those we defined ourselves in Chapter 15. One example of a Java collection
class, which you saw in Chapter 14, is the
class. The
ArrayList<T>
Collection<T>
interface allows you to write code that applies to all Java collections so that you do not
have to rewrite the code for each specific collection type. There are other interfaces and
abstract classes that are in some sense or another produced from the
Collection<T>
Search WWH ::




Custom Search