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
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.
collection
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 ArrayList<T> 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 to understand Swing and GUIs. So,
you may skip this and go directly to Chapter 17 if you prefer to cover Swing GUIs
before considering the material of this chapter.
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 Collection<T> interface. A Java collection is any class that implements the
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
ArrayList<T> class. The 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
 
 
Search WWH ::




Custom Search