Chapter 19 Collection Classes Collections are classes designed - - PDF document

chapter 19 collection classes collections are classes
SMART_READER_LITE
LIVE PREVIEW

Chapter 19 Collection Classes Collections are classes designed - - PDF document

Chapter 19 Collection Classes Collections are classes designed for holding groups of ob jects. Almost all non trivial programs need to main tain one or more collections of ob jects. Although the Ja v a library pro


slide-1
SLIDE 1 Chapter 19 Collection Classes Collections are classes designed for holding groups
  • f
  • b
jects. Almost all non trivial programs need to main tain
  • ne
  • r
more collections
  • f
  • b
jects. Although the Ja v a library pro vides
  • nly
a few dieren t forms
  • f
collection, the features pro vided b y these classes are v ery general, making them applicable to a wide v ariet y
  • f
problems. In this c hapter w e will rst describ e some
  • f
the basic concepts common to the collection classes, then summarize the basic collections pro vided b y Ja v a, and nally describ e a few con tainer t yp es that are not pro vided b y the standard library , but whic h can b e easily constructed b y the programmer. 19.1 Elemen ts T yp es and primitiv e v alue W rapp ers With the exception
  • f
the a rra y data t yp e, all the collections pro vided b y the Ja v a library main tain their v alues in v ariables
  • f
t yp e Object. There are t w
  • imp
  • rtan
t consequences
  • f
this feature:
  • Since
primitiv e t yp es, suc h as in tegers, b
  • leans,
c haracters and
  • ating
p
  • in
t v alues, are not sub classes
  • f
Object, they cannot b e directly stored in these collections.
  • When
v alues are remo v ed from the collection, they m ust b e cast bac k to their
  • riginal
t yp e. One w a y to circum v en t the rst restriction is through the use
  • f
wr app er classes. A wrapp er class main tains a primitiv e data v alue, but is itself an
  • b
ject, and can th us b e stored in a con tainer. Metho ds are t ypically pro vided to b
  • th
to construct an instance
  • f
the wrapp er class from a primitiv e v alue, and to reco v er the
  • riginal
v alue from the wrapp er. The follo wing, for example, stores t w
  • in
tegers in to instances
  • f
class Integer, then reco v ers the
  • riginal
v alues so that an arithmetic
  • p
eration can b e p erformed: 317
slide-2
SLIDE 2 318 CHAPTER 19. COLLECTION CLASSES Integer wrapp er new Integer(int value) build Integer from int Integer(String value) parse in teger in String intV alue() v alue
  • f
Integer as int toString() return decimal string represen tation
  • f
Integer toBina ryString() return binary represen tation toOctalString() return
  • ctal
represen tation toHexString() return hex represen tation Cha racter wrapp er new Cha racter(cha r value) con v ert cha r to Cha racter cha rV alue() return cha r v alue
  • f
Cha racter isLetter() determine if c haracter is letter isDigit() true if c haracter is digit Bo
  • lean
wrapp er new Bo
  • lean
(b
  • lean
value) con v ert b
  • lean
to Bo
  • lean
b
  • leanV
alue () retriev e b
  • lean
v alue from Bo
  • lean
toString() generate string represen tation
  • f
b
  • lean
Double wrapp er new Double(double) con v ert double to Double new Double(String) construct Double from string doubleV alue() return double v alue
  • f
Double Figure 19.1: W rapp er Classes and Selected Beha viors Integer a = new Integer(12); Integer b = new Integer(3); // m ust reco v er the in t v alues to do arithmetic int c = a.intValue()
  • b.intValue();
In addition, man y wrapp er classes pro vide
  • ther
useful functionalit y , suc h as the abilit y to parse string v alues. A common w a y to con v ert a string con taining an in teger v alue literal in to an int, for example, is to use an Integer as a middle step: String text = "123"; // example string v alue Integer val = new Integer(text); // rst con v ert to In teger int ival = val.intValue(); // then con v ert In teger to in t Figure 19.1 summarizes the most common wrapp er classes and a few
  • f
their more useful b eha viors.
slide-3
SLIDE 3 19.2. ENUMERA TORS 319 19.2 En umerators All collections can b e en visioned as a linear sequence
  • f
elemen ts, ho w ev er the particular means used to access eac h elemen t diers from
  • ne
collection t yp e to another. F
  • r
example, a v ector is indexed using an in teger p
  • sition
k ey , while a hash table can use an y t yp e
  • f
  • b
ject as a k ey . It is frequen tly desirable to abstract a w a y these dierences, and access the elemen ts
  • f
the collection in sequence without regard to the tec hnique used to
  • btain
the underlying v alues. This facilit y is pro vided b y the Enumeration in terface, and its v arious implemen tations. The Enumeration in terface sp ecies t w
  • metho
ds: hasMo reElements() A b
  • lean
v alue that indicates whether
  • r
not there are an y more elemen ts to b e en umerated nextElement() Retriev es the next elemen t in the en umeration These t w
  • p
erations are used together to form a lo
  • p.
The follo wing, for example, sho ws ho w all the elemen ts
  • f
a hash table could b e prin ted: for (Enumeration e = htab.elements(); e.hasMoreElements () ; ) f System.out.printl n (e.nextElement()) ; g The metho ds hasMo reElements() and nextElement should alw a ys b e in v
  • k
ed in tandem. That is, nextElement should nev er b e in v
  • k
ed unless hasMo reElements has rst determined that there is another elemen t, and nextElement should nev er b e in v
  • k
ed t wice without an in terv ening call
  • n
hasMo reElements. If it is necessary to refer more than
  • nce
to the v alue returned b y nextElement, the result
  • f
the nextElement call should b e assigned to a lo cal v ariable: for (Enumeration e = htab.elements(); e.hasMoreElements () ; ) f Object value = e.nextElement(); if (value.equals(Te st) ) System.out.prin tln ("found
  • bject
" + value); g With the exception
  • f
the arra y , all the collections pro vided b y the Ja v a library pro vide a function that generates an en umeration. In addition, sev eral
  • ther
classes that are not necessarily collections also supp
  • rt
the en umeration proto col. F
  • r
example, a StringT
  • k
enizer is used to extract w
  • rds
from a string v alue. The individual w
  • rds
are then accessed using en umeration metho ds. In Section 19.6.1 w e will describ e ho w the programmer can create a new t yp e
  • f
en umeration.
slide-4
SLIDE 4 320 CHAPTER 19. COLLECTION CLASSES 19.3 The Arra y The most basic collection form in Ja v a is the arra y . As w e ha v e noted in earlier c hapters, the creation and manipulation
  • f
an arra y v alue is dieren t in Ja v a than in man y
  • ther
programming languages. The Ja v a language mak es a separation b et w een (a) declaring a v ariable
  • f
arra y t yp e, (b) dening the size
  • f
the arra y and allo cating space, and (c) assigning v alues to the arra y . In man y
  • ther
languages the rst and second tasks are merged together. Merging these concepts mak es it dicult to, for example, write functions that will
  • p
erate
  • n
arra ys
  • f
an y size. These problems are largely eliminated in Ja v a's approac h to arra ys. An arra y v ariable is declared b y indicating the t yp e
  • f
elemen ts the arra y will con tain, and a pair
  • f
square brac k ets that indicate an arra y is b eing formed. The follo wing, for example, is from the solitaire game case study examined in Chapter 9. static public CardPile allPiles [ ]; The brac k ets can b e written either after the v ariable name,
  • r
after the t yp e. The follo wing, for example, is an equiv alen t declaration: static public CardPile [ ] allPiles; Note that the arra y is the
  • nly
collection in the Ja v a library that requires the programmer to sp ecify the t yp e
  • f
elemen ts that will b e held b y the con tainer. An imp
  • rtan
t consequence
  • f
this is that the arra y is the
  • nly
collection that can main tain non-ob ject t yp es, suc h as in tegers, b
  • leans,
  • r
c haracters. Other con tainers hold their v alues as instances
  • f
class Object, and can therefore
  • nly
hold primitiv e v alues if they are surrounded b y wrapp er classes (Integer, Double, and so
  • n).
An arra y value is created, as are all v alues, using the new
  • p
erator. It is
  • nly
when the arra y v alue is created that the size
  • f
the arra y is sp ecied. allPiles = new CardPile [ 13 ]; // create arra y
  • f
13 card piles Arra ys can also b e created as an initialization expression in the
  • riginal
declaration. The initialization expression pro vides the v alues for the arra y , as w ell as indicating the n um b er
  • f
elemen ts. int primes [ ] = f2, 3, 5, 7. 11, 13, 17, 19g; Elemen ts
  • f
an arra y are accessed using the subscript
  • p
erator. This is used b
  • th
to retriev e the curren t v alue held at a giv en p
  • sition,
and to assign a p
  • sition
a new v alue: primes[3] = primes[2] + 2;
slide-5
SLIDE 5 19.4. THE VECTOR COLLECTION 321 Legal index v alues range from zero to
  • ne
less than the n um b er
  • f
elemen ts held b y the arra y . An attempt to access a v alue with an
  • ut
  • f
range index v alue results in an IndexOutOfBoundsException b eing thro wn. The in teger eld length describ es the n um b er
  • f
elemen ts held b y an arra y . The follo wing lo
  • p
sho ws this v alue b eing used to form a lo
  • p
to prin t the elemen ts in an arra y: for (int i = 0; i < primes.length; i++) System.out.prin tln (" pri me " + i + " is " + primes[i]); Arra ys are also clone able (see Section 11.3.1). An arra y can b e copied, and assigned to another arra y v alue. The clone
  • p
eration creates a shallo w cop y . int numbers [ ]; numbers = primes.clone(); // creates a new arra y
  • f
n um b ers 19.4 The V ecto r collection The V ecto r data abstraction is similar to an arra y
  • f
  • b
jects, ho w ev er it pro vides a n um b er
  • f
high lev el
  • p
erations not supp
  • rted
b y the arra y abstraction. Most imp
  • rtan
tly , a v ector is exp andable, meaning it gro ws as necessary as new elemen ts are added to the collection. Th us, the programmer need not kno w the ev en tual collection size at the time the v ector is created. T
  • use
this collection the V ecto r class m ust b e imp
  • rted
from java.util.V ecto r. A new v ector is created using the new
  • p
erator. import java.util.Vector; ... Vector numbers = new Vector (); Because
  • b
jects held b y a V ecto r m ust b e sub classes
  • f
Object, a v ector can not b e used to hold primitiv e v alues, suc h as in tegers
  • r
  • ats.
Ho w ev er, wrapp er classes can b e used to con v ert suc h v alues in to
  • b
jects. T able 19.1 summarizes the most useful
  • p
erations pro vided b y the V ecto r data abstrac- tion. The class as b een carefully designed so that it can b e used in a v ariet y
  • f
dieren t w a ys. The follo wing sections describ e some
  • f
the more common uses. 19.4.1 Using a V ecto r as an arra y Unlik e an arra y , a v ector is not created with a xed size. A v ector can b e giv en a sp ecic size either b y adding the appropriate n um b er
  • f
elemen ts (using the addElement
  • p
eration)
slide-6
SLIDE 6 322 CHAPTER 19. COLLECTION CLASSES Size Determination size() returns n um b er
  • f
elemen ts in collection isEmpt y() returns true if collection is empt y capacit y() return curren t capacit y
  • f
v ector setSize() set size
  • f
v ector, truncating
  • r
expanding as necessary Elemen t Access contains() determines whether a v alue is in this v ector rstElement() returns rst elemen t
  • f
collection lastElement() returns last elemen t
  • f
collection elementA t(index) returns elemen t stored at giv en p
  • sition
Insertion and Mo dication addElement(value) add new v alue to end
  • f
collection setElementA t(value, index) c hange v alue at p
  • sition
insertElementA t(value, index) insert v alue at giv en index Remo v al removeElementA t(index) remo v e elemen t at index, reducing size
  • f
v ector removeElement(value) remo v e all instances
  • f
v alue removeAllElements() delete all v alues from v ector Searc h indexOf(value) return index
  • f
rst
  • ccurrence
lastIndexOf(value) return index
  • f
last
  • ccurrence
Miscellaneous clone() return shallo w cop y
  • f
v ector toString() return string represen tation
  • f
v ector T able 19.1: Op erations pro vided b y the V ecto r data t yp e
slide-7
SLIDE 7 19.4. THE VECTOR COLLECTION 323
  • r
b y using setSize. In the latter case a null v alue will b e stored in an y index lo cations that ha v e not previously b een assigned a v alue: Vector aVec = new Vector (); // create a new v ector aVec.setSize (20); // allo cate 20 lo cations, initially undened Once sized, the v alue stored at an y p
  • sition
can b e accessed using the metho d elementA t, while p
  • sitions
can b e mo died using setElementA t. Note that in the latter, the index
  • f
the p
  • sition
b eing mo died is the second parameter, while the v alue to b e assigned to the lo cation is the rst parameter. The follo wing illustrates ho w these functions could b e used to sw ap the rst and nal elemen ts
  • f
a v ector: Object first = aVec.elementAt(0) ; // store rst p
  • sition
aVec.setElementAt (a Vec .l ast El eme nt () , 0); // store last in lo cation aVec.setElementAt (f irs t, aVec.size()-1); // store rst at end 19.4.2 Using a V ecto r as a stac k A stack is a data structure that allo ws elemen ts to b e inserted and remo v ed at
  • ne
end, and alw a ys remo v es the last elemen t inserted. A stac k
  • f
pap ers
  • n
a desk is a go
  • d
in tuitiv e picture
  • f
the stac k abstraction. Although the Ja v a standard library includes a Stack data abstraction (see Section 19.5), it is easy to see ho w a V ecto r can b e used as a stac k. The c haracteristic
  • p
erations
  • f
a stac k are to insert
  • r
remo v e an item from the top
  • f
the stac k, p eek at (but do not remo v e) the topmost elemen t, test the stac k for emptiness. The follo wing sho ws ho w eac h
  • f
these can b e p erformed using
  • p
erations pro vided b y the vecto r class: push an v alue
  • n
the stac k aV ec.addElement (value) p eek at the topmost elemen t
  • f
the stac k aV ec.lastElement() remo v e the topmost elemen t
  • f
the stac k aV ec.removeElementA t(aV ec.size()
  • 1)
As w e will note in Section 19.5, the Stack abstraction is sligh tly more robust, since it will thro w more meaningful error indications if an attempt is made to remo v e an elemen t from an empt y stac k. 19.4.3 Using a V ecto r as a queue A queue is a data structure that allo ws elemen ts to b e inserted at
  • ne
end, and remo v ed from the
  • ther.
In this fashion, the elemen t remo v ed will b e the rst elemen t that w as inserted. Thinking ab
  • ut
a line
  • f
p eople w aiting to en ter a theater pro vides a go
  • d
in tuition. In a manner analogous to the w a y that the v ector can b e used as a stac k, the v ector
  • p
erations can also b e used to sim ulate a queue:
slide-8
SLIDE 8 324 CHAPTER 19. COLLECTION CLASSES push an v alue
  • n
the queue aV ec.addElement (value) p eek at the rst elemen t in the queue aV ec.rstElement() remo v e the rst elemen t
  • f
the queue aV ec.removeElementA t(0) There is
  • ne
imp
  • rtan
t dierence b et w een this abstraction and the earlier sim ulation
  • f
the stac k. In the stac k abstraction, all the
  • p
erations could b e p erformed in constan t time, indep enden t
  • f
the n um b er
  • f
elemen ts b eing held b y the stac k. 1 Remo ving the rst elemen t from the queue,
  • n
the
  • ther
hand always results in all elemen ts b eing mo v ed, and is therefore alw a ys requires time prop
  • rtional
to the n um b er
  • f
elemen ts in the collection. 19.4.4 Using a V ecto r as a set A set is usually en visioned as an unordered collection
  • f
v alues. Characteristic
  • p
erations
  • n
a set include testing to see if a v alue is b eing held in the set, and adding
  • r
remo ving v alues from the set. The follo wing sho ws ho w these can b e implemen ted using the
  • p
erations pro vided b y the V ecto r class: see if v alue is held in set aV ec.contains(value) add new elemen t to set aV ec.addElement(value) remo v e elemen t from set aV ec.removeElement(value) The equals metho d is used to p erform comparisons. Comparisons are necessary to de- termine whether
  • r
not a v alue is held in the collection, and whether a v alue is the elemen t the user wishes to delete. F
  • r
user dened data v alues the equals metho d can b e
  • v
erridden to pro vide whatev er meaning is appropriate (see Section 11.4). Op erations suc h as union and in tersection
  • f
sets can b e easily implemen ted using a lo
  • p.
The follo wing, for example, places in setThree the union
  • f
the v alues from setOne and setTw
  • .
Vector setThree = new Vector(); setThree = setOne.clone(); // rst cop y all
  • f
set
  • ne
// then add elemen ts from set t w
  • not
already in set
  • ne
for (Enumeration e = setTwo.elements (); e.hasMoreElement s( ); ) f Object value = e.nextElement(); if (! setThree.contains (v alu e) ) setThree.addElem ent (v alu e) ; g F
  • r
sets consisting
  • f
p
  • sitiv
e in teger v alues, the BitSet class (Section 19.6 is
  • ften
a more ecien t alternativ e. 1 The assertion concerning constan t time
  • p
eration
  • f
stac k
  • p
erations is true with
  • ne
small ca v eat. An insertion can, in rare
  • ccasions,
result in a reallo cation
  • f
the underlying v ector buer, and th us require time prop
  • rtional
to the n um b er
  • f
elemen ts in the v ector. Th us is usually , ho w ev er, a rare
  • ccurrence.
slide-9
SLIDE 9 19.5. THE ST A CK COLLECTION 325 19.4.5 Using a V ecto r as a list Characteristic
  • p
erations
  • f
a list data abstraction are the abilities to insert
  • r
remo v e elemen ts at an y lo cation, and the abilit y to nd the lo cation
  • f
an y v alue. 2 rst elemen t aV ec.rstElement() last elemen t aV ec.lastElement() insert to fron t
  • f
list aV ec.insertElementA t(value, 0) insert to end
  • f
list aV ec.addElement(value) see if v alue is in collection aV ec.contains(value) remo v e rst elemen t aV ec.removeElementA t(0) remo v e last elemen t aV ec.removeElementA t(aV ec.size()
  • 1)
nd lo cation
  • f
elemen t aV ec.indexOf(value) remo v e v alue from middle aV ec.removeElementA t(index) Again, this use
  • f
the V ecto r abstraction to sim ulate a list diers from the classical description
  • f
the list abstraction in the algorithmic execution time
  • f
certain
  • p
erations. In particular, the insertion
  • r
remo v al from the fron t
  • f
the collection ma y result in the en tire set
  • f
v alues b eing mo v ed, thereb y requiring time prop
  • rtional
to the size
  • f
the collection. This is
  • nly
a critical concern when the size
  • f
the collections is large
  • r
when this is a frequen t
  • p
eration. A more direct implemen tation
  • f
a list is describ ed in Section 19.9. 19.5 The Stack collection Section 19.4.2 describ ed ho w a stac k could b e sim ulated using a V ecto r. Ho w ev er, the Ja v a standard library also pro vides the Stack as a data v alue. The names
  • f
the metho ds used to
  • p
erate
  • n
this data t yp e are sligh tly dieren t from the V ecto r
  • p
erations describ ed in Section 19.4.2, and the structure is sligh tly more robust. Stac k
  • p
erations can b e describ ed as follo ws: create a new stac k Stack aStack = new Stack() push an v alue
  • n
to the stac k aStack.push (value) p eek at the topmost elemen t
  • f
the stac k aStack.p eek() remo v e the topmost elemen t
  • f
the stac k aStack.p
  • p()
n um b er
  • f
elemen ts in the collection aStack.size() test for empt y stac k aStack.empt y() p
  • sition
  • f
elemen t in stac k aStack.sea rch(value) The p
  • p
  • p
eration b
  • th
remo v es and returns the topmost elemen t
  • f
the stac k. Both the p
  • p
and the p eek
  • p
erations will thro w an Empt yStackException if they are applied to an empt y stac k. 2 The list referred to here is the traditional data abstraction kno wn b y that name. The Ja v a library unfortunately uses the class name List to refer to a graphical comp
  • nen
t that allo ws the user to select a v alue from a series
  • f
string items.
slide-10
SLIDE 10 326 CHAPTER 19. COLLECTION CLASSES The sea rch metho d returns the index
  • f
the giv en elemen t starting from the top
  • f
the stac k; that is, if the elemen t is found at the top
  • f
the stac k searc h will return 0, if found
  • ne
elemen t do wn in the stac k searc h will return 1, and so
  • n.
Because the Stack data structure is built using inheritance from the V ecto r class it is also p
  • ssible
to access the v alues
  • f
the stac k using their index. Ho w ev er, the p
  • sitions
returned b y the sea rch
  • p
eration do not corresp
  • nd
to the index p
  • sition.
T
  • disco
v er the index p
  • sition
  • f
a v alue the V ecto r
  • p
eration indexOf can b e used. In Chapter 10 w e describ ed some
  • f
the adv an tages and disadv an tages
  • f
creating the stac k using inheritance from class V ecto r. 19.6 The BitSet collection A BitSet is abstractly a set
  • f
p
  • sitiv
e in teger v alues. The BitSet class diers from the
  • ther
collection classes in that it can
  • nly
b e used to hold in teger v alues. Lik e an arra y
  • r
a V ecto r, eac h elemen t is giv en an index p
  • sition.
Ho w ev er, the
  • nly
  • p
erations that can b e p erformed
  • n
eac h elemen t are to set, test
  • r
clear the v alue. A BitSet is a compact w a y to enco de either a collection
  • f
p
  • sitiv
e in teger v alues,
  • r
a collection
  • f
b
  • lean
v alues (for example,
  • n/o
settings). A create a BitSet the user can sp ecify the n um b er
  • f
p
  • sitions
the set will represen t. Ho w ev er, lik e the V ecto r, the bit set is extensible, and will b e enlarged automatically if a p
  • sition
  • utside
the range is accessed. // create a BitSet that initially con tains 75 elemen ts BitSet bset = new BitSet(75); The follo wing table summarizes the
  • p
erations used to set
  • r
test an individual p
  • sition
in the bit set: set a bit p
  • sition
bset.set (index) test a bit p
  • sition
bset.get (index) clear a bit p
  • sition
bset.clea r (index) The get metho d returns a b
  • lean
v alue, whic h is true if the giv en bit is set, and false
  • therwise.
Eac h
  • f
these
  • p
erations will thro w an IndexOutOfBoundsException if the index v alue is smaller than zero. A BitSet can b e com bined with another BitSet in a v ariet y
  • f
w a ys: F
  • rm
bit wise union with argumen t set bset.o r(setTw
  • )
F
  • rm
bit wise in tersection with argumen t set bset.and(setTw
  • )
F
  • rm
bit wise symmetric dierence with argumen t set bset.xo r(setTw
  • )
The metho d toString returns the string represen tation
  • f
the collection. This consists
  • f
a comma-separated list
  • f
the indices
  • f
the bits in the collection that ha v e b een set.
slide-11
SLIDE 11 19.7. THE DICTIONARY INTERF A CE AND THE HASHT ABLE COLLECTION 327 19.6.1 Example Program: Prime Siev e A program that will generate a list
  • f
prime n um b ers using the siev e
  • f
Erasthones can b e used to illustrate the manipulation
  • f
a bit set. The constructor for the class Sieve (Figure 19.2) tak es an in teger argumen t n, and creates a bit set
  • f
n p
  • sitions.
These are initially all set to
  • ne,
using the mem b er function set. The siev e algorithm then w alks through the list, using get to nd the next set v alue. A lo
  • p
then w alks through the remainder
  • f
the collection, thro wing
  • ut
(via the clea r() mem b er function) v alues whic h are m ultiples
  • f
the earlier v alue. When w e are nished, an y v alue not crossed
  • ut
m ust b e prime. The remaining t w
  • functions
illustrate ho w a new en umeration can b e created. The v alue index will main tain the curren t \p
  • sition"
in the list, whic h will c hange as v alues are en umerated. The function hasMo reElements lo
  • ps
un til a prime v alue is found,
  • r
un til the size
  • f
the bit set is exceeded. The rst results in a true v alue, the latter a false
  • ne.
The metho d nextElement simply mak es an
  • b
ject
  • ut
  • f
the in teger v alue. A small test metho d is also included in the class, to illustrate ho w this class could b e used. 19.7 The Dictiona ry in terface and the Hashtable collection A dictionary is an indexed collection, similar to an arra y
  • r
a V ecto r. Ho w ev er, unlik e an arra y , the index v alues need not b e in teger. Instead, an y
  • b
ject t yp e can b e used as in index (called a key), and an y
  • b
ject v alue can b e stored as the elemen t selected b y the k ey . T
  • place
a new v alue in to the collection the user pro vides b
  • th
the k ey and v alue. T
  • access
an elemen t in the collection the user pro vides a k ey , and the asso ciated v alue is returned. In the Ja v a library the class Dictiona ry is an abstract class that denes the b eha vior
  • f
the dictionary abstraction, but do es not pro vide an implemen tation. This in terface can b e describ ed as follo ws: retriev e v alue asso ciated with giv en k ey dict.get(k ey) place v alue in to collection with giv en k ey dict.put(k ey , value) remo v e v alue from collection dict.remove(k ey) see if collection is empt y dict.isEmpt y() return n um b er
  • f
elemen ts in collection dict.size() return en umeration for collection v alues dict.elements() return en umeration
  • f
collection k eys dict.k eys() The get metho d will return null if the giv en v alue is not found in the collection. Otherwise, the v alue is returned as an Object, whic h m ust then b e cast in to the appropriate t yp e. The remove metho d returns the v alue
  • f
the asso ciation b eing deleted, again returning null if the k ey is not a legal index elemen t. There are t w
  • en
umeration generating metho ds,
  • ne
to return an en umeration
  • f
k eys, and
  • ne
to return an en umeration
  • f
v alues. The class Hashtable pro vides an implemen tation
  • f
the Dictiona ry
  • p
erations. A hash table can b e en visioned as an arra y
  • f
collections, called buckets. T
  • add
an elemen t to
slide-12
SLIDE 12 328 CHAPTER 19. COLLECTION CLASSES import java.util.; class Sieve implements Enumeration f private BitSet primes; private int index = 2; public Sieve (int n) f primes = new BitSet(n); // rst set all the bits for (int i = 1; i < n; i++) primes.set(i); // then erase all the non-primes for (int i = 2; i
  • i
< n; i++) if (primes.get(i)) for (int j = i + i; j <= n; j += i) primes.clear(j); g public boolean hasMoreElements () f index++; int n = primes.size(); while (! primes.get(index )) if (++index > n) return false; return true; g public Object nextElement() f return new Integer(index); g // test program for prime siev e algorithm public static void main (String [ ] args) f Sieve p = new Sieve(100); while (p.hasMoreElement s( )) System.out.print ln( p. nex tE le men t( )); g g Figure 19.2: Prime Siev e program
slide-13
SLIDE 13 19.7. THE DICTIONARY INTERF A CE AND THE HASHT ABLE COLLECTION 329 the collection, an in teger v alue, called the hash value, is rst computed for the giv en k ey . The metho d hashCo de is used for this purp
  • se.
This metho d is dened in class Object, and is therefore common to all
  • b
ject v alues. It is
  • v
erridden in v arious classes to pro vide alternativ e algorithms. Using this in teger,
  • ne
  • f
the buc k ets is selected and the k ey/v alue pair inserted in to the corresp
  • nding
collection. In addition to the metho ds matc hing the Dictiona ry sp ecication, the hash table pro vides the metho d clea r(), whic h remo v es all v alues from the con tainer, contains(value), whic h determines whether an elemen t is con tained in the collection, and containsKey(k ey), whic h tests to see if a giv en k ey is in the collection. The default implemen tation
  • f
the hashCo de metho d, in class Object, should b e applicable in almost all situations, just as the default implemen tation
  • f
equals is usually adequate. If a data t yp e that is going to b e used as a hash table k ey
  • v
errides the equals metho d, it is a go
  • d
idea to also
  • v
erride hashCo de, so that t w
  • b
jects that test equal to eac h
  • ther
will also ha v e the same hash v alue. 19.7.1 Example Program: A Concordance A concordance is a listing
  • f
w
  • rds
from a prin ted text, eac h w
  • rd
b eing follo w ed b y the lines
  • n
whic h the w
  • rd
app ears. A class that will create a concordance will illustrate ho w the Dictiona ry data t yp e is used, as w ell as ho w dieren t collection classes can b e com bined with eac h
  • ther.
In the program sho wn in Figure 19.3, the primary data structure is a dictionary , im- plemen ted using the Hashtable class. The k eys for this dictionary will b e the individual w
  • rds
in the input text. The v alue asso ciated with eac h k ey will b e a set
  • f
in teger v alues, represen ting the line n um b ers
  • n
whic h the w
  • rd
app ears. A V ecto r will b e used to represen t the set, using the tec hniques describ ed in Section 19.4.4. The metho d readLines reads the input line b y line, main taining a coun ter to indicate the line n um b er. The metho d readLine, pro vided b y the class DataInputStream, returns a null v alue when end
  • f
input is encoun tered, at whic h time the metho d returns. (This metho d is also the p
  • ten
tial source for the IOException, whic h can b e thro wn if an error
  • ccurs
during the read
  • p
eration. In
  • ur
program w e simply pass this exception bac k to the caller). Otherwise, the text is con v erted to lo w er case, using the metho d toLo w erCase pro vided b y the String class, then a StringT
  • k
enizer is created to split the text in to individual w
  • rds.
A StringT
  • k
enizer is a form
  • f
Enumeration, and so an en umeration lo
  • p
is used to en ter eac h w
  • rd
in to the concordance. The priv ate metho d enterW
  • rd
is used to place eac h new w
  • rd
in the concordance. First, the v alue asso ciated with the k ey (the w
  • rd)
is determined. Here the program handles the rst
  • f
t w
  • exceptional
conditions that migh t arise. If this is the rst time the w
  • rd
has b een seen, there will b e no en try in the dictionary , and so result
  • f
calling get will b e a null v alue. In this case a new and empt y V ecto r is created, and inserted in to the dictionary using the w
  • rd
as k ey . Using the V ecto r in the fashion
  • f
a set, the metho d contains is in v
  • k
ed to determine if the line has already b een placed in the collection. (This is the
slide-14
SLIDE 14 330 CHAPTER 19. COLLECTION CLASSES import java.util.; import java.io.; class Concordance f private Dictionary dict = new Hashtable(); public void readLines (DataInputStream input) throws IOException f String delims = " \t\n.,!?;:"; for (int line = 1; true; line++ ) f String text = input.readLine(); if (text == null) return; text = text.toLowerCase( ); Enumeration e = new StringTokenizer( te xt , delims); while (e.hasMoreEleme nts () ) enterWord ((String) e.nextElement(), new Integer(line)); g g public void generateOutput (PrintStream
  • utput)
f Enumeration e = dict.keys(); while (e.hasMoreElement s( ) ) f String word = (String) e.nextElement() ; Vector set = (Vector) dict.get(word);
  • utput.print
(word + ": "); Enumeration f = set.elements(); while (f.hasMoreEleme nts () )
  • utput.print
(f.nextElement() + " ");
  • utput.println
(" "); g g private void enterWord (String word, Integer line) f Vector set = (Vector) dict.get(word); if (set == null) f // w
  • rd
not in collection set = new Vector(); // mak e new set dict.put (word, set); g if (! set.contains(line )) set.addElement(l in e); g g Figure 19.3: The class Conco rdance
slide-15
SLIDE 15 19.7. THE DICTIONARY INTERF A CE AND THE HASHT ABLE COLLECTION 331 second exceptional condition, whic h will
  • ccur
if the same w
  • rd
app ears t w
  • r
more times
  • n
  • ne
line.) If not, the line is then added to the list. Finally ,
  • nce
all the input has b een pro cessed, the metho d generateOutput is used to create the prin ted rep
  • rt.
This metho d uses a doubly-nested en umeration lo
  • p.
The rst lo
  • p
en umerates the k eys
  • f
the Dictiona ry, generated b y the k eys metho d. The v alue asso- ciated with eac h k ey is a set, represen ted b y a V ecto r. A second lo
  • p,
using the en umerator pro duced b y the elements metho d, then prin ts the v alues held b y the v ector. An easy w a y to test the program is to use the system resources System.in and System.out as the input and
  • utput
con tainers, as in the follo wing: static public void main (String [ ] args) f Concordance c = new Concordance(); try f c.readLines(new DataInputStream(S yst em .i n)) ; g catch (IOException e) f return; g c.generateOutpu t (System.out); g 19.7.2 Prop erties The Ja v a run-time system main tains a sp ecial t yp e
  • f
hash table, termed the pr
  • p
erties list. The class Prop erties, a sub class
  • f
Hashtable, holds a collection
  • f
string k ey/v alue pairs. These represen t v alues the describ e the curren t executing en vironmen t, suc h as the user name,
  • p
erating system name, home directory , and so
  • n.
The follo wing program can b e used to see the range
  • f
prop erties a v ailable to a running Ja v a program: public static void main (String [ ] args) f Dictionary props = System.getProper ti es( ); Enumeration e = props.keys(); while (e.hasMoreElement s( )) f Object key = e.nextElement() ; Object value = props.get(key); System.out.print ln( "p rop er ty " + key + " value " + value); g g
slide-16
SLIDE 16 332 CHAPTER 19. COLLECTION CLASSES 19.8 Wh y are there no
  • rdered
collections? If
  • ne
considers the \classic" data abstractions found in most data structures textb
  • ks,
a notable
  • mission
from the Ja v a library are data structures that main tain v alues in sequence. Examples
  • f
suc h abstractions are
  • rdered
lists,
  • rdered
v ectors,
  • r
binary trees. Indeed, there is not ev en an y mec hanism pro vided in the Ja v a library to sort a v ector
  • f
v alues. Rather than b eing caused b y
  • v
ersigh t, this
  • mission
reects some fundamen tal prop erties
  • f
the Ja v a language. All
  • f
the Ja v a collections main tain their v alues in v ariables
  • f
t yp e Object. The class Object do es not dene an y
  • rdering
relation. Indeed, the
  • nly
elemen ts that can b e com- pared using the <
  • p
erator are the primitiv e n umeric t yp es (in teger, long, double, and so
  • n).
One could imagine dening in class Object a metho d lessThan(Object), similar to the metho d equals(Object). Ho w ev er, while there is a clear default in terpretation for the equal- it y
  • p
erator (namely ,
  • b
ject iden tit y), it is dicult to imagine a similar meaning for the relational
  • p
erator that w
  • uld
b e applicable to all
  • b
jects. Certainly it could not pro vide a total
  • rdering
  • n
all
  • b
jects. What, for example, w
  • uld
b e the result
  • f
comparing the String "abc" and the in teger 37? In short,
  • rdered
collections are not found in the Ja v a library b ecause there is no
  • b
vious general mec hanism to dene what it means to
  • rder
t w
  • v
alues. One could imagine that an alternativ e to placing the metho d lessThan in class Object w
  • uld
b e to create an Ordered in terface, suc h as the follo wing: interface Ordered f public boolean compare (Ordered arg); g One could then create a collection in whic h all v alues need to implemen t the Ordered in terface, rather than simply b eing Object. Ho w ev er, there are t w
  • ma
jor
  • b
jections to this tec hnique. The rst is that since the argumen t is
  • nly
kno wn to b e an
  • b
ject that implemen ts the Ordered in terface,
  • ne
m ust still decide ho w to compare
  • b
jects
  • f
dieren t t yp es (a T riangle and an Orange, for example). The second problem is that b y restricting the t yp e
  • f
  • b
jects the collection can main tain to
  • nly
those v alues that implemen t the Ordered relation,
  • ne
sev erely limits the utilit y
  • f
the classes. Another p
  • ssibilit
y is to imagine an in terface for an
  • b
ject that is used to create com- parisons. That is, the
  • b
ject tak es b
  • th
v alues as argumen ts, and returns their
  • rdering.
Suc h an in terface could b e written as follo ws: interface ComparisonObject f public boolean Compare (Object
  • ne,
Object two); g
slide-17
SLIDE 17 19.8. WHY ARE THERE NO ORDERED COLLECTIONS? 333 T
  • manipulate
an
  • rdered
collection,
  • ne
w
  • uld
then create an implemen tation
  • f
this in terface for the desired elemen ts. The follo wing, for example, w
  • uld
b e a comparison class for Integer
  • b
jects: class IntegerComparis
  • n
implements ComparisonObjec t f public boolean Compare (Object
  • ne,
Object two) f if ((one instanceof Integer) && (two instanceof Integer)) f Integer ione = (Integer)
  • ne;
Integer itwo = (Integer) two; return ione.intValue() < itwo.intValue() ; g return false; g g The follo wing program illustrates ho w suc h an
  • b
ject could b e used. The static metho d so rt is an implemen tation
  • f
the insertion sort algorithm. The main metho d creates a v ector
  • f
in teger v alues, then creates a comparison
  • b
ject to b e passed as argumen t to the so rt algorithm. The sorting algorithm
  • rders
the elemen ts in place, using the comparison
  • b
ject to determine the relativ e placemen t
  • f
v alues. class VectorSort f public static void sort (Vector v, ComparisonObject test) f //
  • rder
a v ector using insertion sort int n = v.size(); for (int top = 1; top < n; top++) f for (int j = top-1; j >= && test.Compare(v.el eme nt At (j+ 1) , v.elementAt(j)) ; j--) f // sw ap the elemen ts Object temp = v.elementAt(j+1 ); v.setElementAt(v. ele me nt At( j) , j+1); v.setElementAt(te mp, j); g g g public static void main (String [ ] args) f Vector v = new Vector(); Random r = new Random(); for (int i = 0; i < 10; i++) v.addElement(new Integer(r.nextIn t() )) ;
slide-18
SLIDE 18 334 CHAPTER 19. COLLECTION CLASSES // sort the v ector sort (v, new IntegerComparison () ); for (Enumeration e = v.elements(); e.hasMoreElements () ; ) System.out.print ln( e. nex tE le men t( )); g g 19.9 Building y
  • ur
Own Con tainers Although the con tainers in the Ja v a library are exible, they nev ertheless cannot handle all situations in whic h a collection class is needed. It is therefore sometimes necessary to create new collection classes. W e will illustrate ho w this can b e done b y creating a class that implemen ts the idea
  • f
a link ed list. The ma jor adv an tage
  • f
the link ed list
  • v
er a v ector is that insertions
  • r
remo v als to the b eginning
  • r
the middle
  • f
a link ed list can b e p erformed v ery rapidly (tec hnically , in constan t time). In the v ector these
  • p
erations require the mo v emen t
  • f
all the elemen ts in the collection, and can therefore b e m uc h more costly if the collection is large. The Link edList class abstraction is sho wn in Figure 19.4. 3 The actual v alues are stored in instances
  • f
class Link, whic h is a nested inner class. In addition to a v alue, links main tain references to the previous and next elemen t in the list. A priv ate in ternal v alue rstLink will reference the rst link. A link with an empt y v alue is used to mark the end
  • f
the list. The priv ate in ternal v alue lastLink p
  • in
ts to this v alue. V alues can b e inserted either to the fron t
  • r
the bac k
  • f
the list. An en umeration v alue can also b e used to insert new elemen ts in to the middle
  • f
a list. The v alue is inserted immediately b efore the elemen t referred to b y the en umeration. All three metho ds mak e use
  • f
a common insertion routine pro vided b y the inner class Link. This metho d is also used to main tain the coun t
  • f
the n um b er
  • f
elemen ts in the list. The classes Link and ListEnumeration are sho wn in Figure 19.5. The class ListEnumeration implemen ts the Enumeration proto col, and is used for iter- ating
  • v
er list elemen ts. Note that the Enumeration proto col assumes that the metho ds hasMo reElements and nextElement will w
  • rk
in tandem, and do es not sp ecify whic h
  • f
the t w
  • will
actually adv ance the in ternal reference to the next elemen t. Implemen tations
  • f
the Enumeration proto col use a v ariet y
  • f
dieren t sc hemes. This is wh y , for example,
  • ne
should nev er in v
  • k
e nextElement t wice without an in terv ening call
  • n
hasMo reElements. In the Link edList class, ho w ev er, w e assume that ha ving examined the curren t v alue (the v alue 3 It w
  • uld
ha v e b een preferable to call this class List. Ho w ev er, has w e noted in an earlier fo
  • tnote,
the Ja v a library already has a List class, that implemen ts a graphical comp
  • nen
t used for selecting
  • ne
string item
  • ut
  • f
man y alternativ es.
slide-19
SLIDE 19 19.9. BUILDING YOUR O WN CONT AINERS 335 class LinkedList f private Link firstLink; private Link lastLink; private int count = 0; public LinkedList () f firstLink = lastLink = new Link(null, null, null); g private class Link f ... g private class ListEnumeration implements Enumeration f ... g public boolean isEmpty () f return firstLink == lastLink; g public int size () f return count; g public Object firstElement () f return firstLink.value; g public Object lastElement () f return lastLink.prev.v alu e; g public void addFront (Object newValue) f firstLink.insert( ne wVa lu e); g public void addBack (Object newValue) f lastLink.insert( ne wV alu e) ; g public void addElement (Enumeration e, Object newValue) f ListEnumeration le = (ListEnumeration ) e; le.link.insert (newValue); g public Object removeFront () f return firstLink.remov e() ; g public Object removeBack () f return lastLink.prev.re mov e( ); g public Object removeElement (Enumeration e) f ListEnumeration le = (ListEnumeration ) e; return le.link.remove (); g public Enumeration elements () f return new ListEnumeration( ); g g Figure 19.4: The Link ed List Class
slide-20
SLIDE 20 336 CHAPTER 19. COLLECTION CLASSES class LinkedList f private class Link f public Object value; public Link next; public Link prev; public Link (Object v, Link n, Link p) f value = v; next = n; prev = p; g public void insert (Object newValue) f Link newNode = new Link (newValue, this, prev); count++; if (prev == null) firstLink = newNode; else prev.next = newNode; prev = newNode; g public Object remove () f if (next == null) return null; // cannot remo v e last elemen t count--; next.prev = prev; if (prev == null) firstLink = next; else prev.next = next; return value; g g private class ListEnumeration implements Enumeration f public Link link = null; public boolean hasMoreElements () f if (link == null) link = firstLink; else link = link.next; return link.next != null; g public Object nextElement () f return link.value; g g ... g Figure 19.5: The Inner Classes in Link edList
slide-21
SLIDE 21 19.9. BUILDING YOUR O WN CONT AINERS 337 yielded b y nextElement) the programmer ma y wish to either insert a new v alue
  • r
remo v e the curren t v alue. Th us, in this case the task
  • f
adv ancing to the next v alue is giv en to the metho d hasMo reElements. Chapter Summary In this c hapter w e ha v e describ ed the classes in the Ja v a library that are used to hold collections
  • f
v alues. The simplest collection is the arra y . An arra y is a linear, indexed homogeneous collection. A dicult y with the arra y is that the size
  • f
an arra y is xed at the time the arra y is created. The V ecto r class
  • v
ercomes this restriction, gro wing as necessary as new v alues are added to the collection. V ectors can b e used to represen t sets, queues, and lists
  • f
v alues. The Stack datat yp e is a sp ecialization
  • f
the v ector used when v alues are added and remo v ed from the collection is a strict rst-in, rst-out fashion. A BitSet is a set
  • f
p
  • sitiv
e in teger v alues. A Dictiona ry is an in terface that describ es a collection
  • f
k ey and v alue pairs. The HashT able is
  • ne
p
  • ssible
implemen tation
  • f
the Dictiona ry in terface. The lac k
  • f
an y
  • rdered
collections is a reection
  • f
the problem that there is, in general, no w a y to construct an
  • rdering
among all Ja v a v alues. The c hapter concludes b y sho wing ho w new collection classes can b e created, using as an example a Link ed List con tainer. Study Questions 1. What are collection classes used for? 2. Because the standard library collection classes main tain their v alues as an Object, what m ust b e done to a v alue when it is remo v ed from a collection? 3. What is a wrapp er class? 4. What is an en umerator? 5. What is the proto col for the class Enumerato r? Ho w are these metho ds com bined to form a lo
  • p?
6. Ho w is the Ja v a arra y dieren t from arra ys in
  • ther
languages? 7. What do es it mean to sa y that the V ecto r data t yp e is expandable? 8. Ho w do es the use
  • f
the Stack data t yp e dier from the use
  • f
a V ecto r as a stac k? 9. What concept do es the class BitSet represen t? 10. What is the relationship b et w een the classes Dictiona ry and Hashtable? 11. Wh y are there no
  • rdered
collections in the Ja v a library?
slide-22
SLIDE 22 338 CHAPTER 19. COLLECTION CLASSES Exercises 1. Assume t w
  • sets
are implemen ted using v ectors, as describ ed in Section 19.4.4. W rite a lo
  • p
that will place the in tersection
  • f
the t w
  • sets
in to a third set. 2. Assume t w
  • sets
are implemen ted using v ectors, as describ ed in Section 19.4.4. W rite a lo
  • p
that will place the symmetric dierence
  • f
the t w
  • sets
in to a third set. (The symmetric dierence is the set
  • f
elemen ts that are in
  • ne
  • r
the
  • ther
set, but not b
  • th).
3. Add the follo wing metho ds to the Link edList class describ ed in Section 19.9: setElement(Enumeration e, Object v) c hange v alue at giv en lo cation includes(Object v) test whether v alue is in collection nd(Object v) return en umeration if v alue is in collection,
  • r
n ull 4. Mo dify the Link edList class
  • f
Section 19.9 so that link ed lists supp
  • rt
the cloneable in terface. (The cloneable in terface is describ ed in Section 11.3.1). 5. W rite an OrderedList class. This class will b e lik e a link ed list, but will main tain a comparison
  • b
ject, as describ ed in Section 19.8. Using this
  • b
ject, elemen ts will b e placed in sequence as they are inserted in to the con tainer.