Instant Download Data Structures and the Java Collections Frameworks 3rd Edition William J. Collins PDF All Chapters
Instant Download Data Structures and the Java Collections Frameworks 3rd Edition William J. Collins PDF All Chapters
com
https://ebookname.com/product/data-structures-and-the-java-
collections-frameworks-3rd-edition-william-j-collins/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/object-oriented-data-structures-using-
java-chip-weems/
ebookname.com
https://ebookname.com/product/data-structures-and-abstractions-with-
java-4th-edition-frank-m-carrano/
ebookname.com
https://ebookname.com/product/java-methods-a-ab-object-oriented-
programming-and-data-structures-maria-litvin/
ebookname.com
https://ebookname.com/product/10-minute-guide-to-pocket-pc-2002-1st-
edition-michael-miller/
ebookname.com
https://ebookname.com/product/the-behavioral-foundations-of-public-
policy-7th-edition-shafir/
ebookname.com
https://ebookname.com/product/the-living-gut-second-edition-w-n-ewing/
ebookname.com
https://ebookname.com/product/top-10-paris-eyewitness-top-10-travel-
guides-1-pap-map-edition-mike-gerrard/
ebookname.com
https://ebookname.com/product/how-do-you-hug-a-cactus-reflective-
parenting-with-teenagers-in-mind-1st-edition-sheila-redfern/
ebookname.com
Lessons from a Quechua Strongwoman Ideophony Dialogue and
Perspective 1st Edition Janis B. Nuckolls
https://ebookname.com/product/lessons-from-a-quechua-strongwoman-
ideophony-dialogue-and-perspective-1st-edition-janis-b-nuckolls/
ebookname.com
This page intentionally left blank
Data Structures and the
Java Collections Framework
This page intentionally left blank
Data Structures and the
Java Collections Framework
Third Edition
William J. Collins
Lafayette College
This book was set in 10/12 Times Roman by Laserwords and printed and bound by Malloy Lithographers. The cover was printed by Malloy
Lithographers.
Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more than 200 years, helping
people around the world meet their needs and fulfill their aspirations. Our company is built on a foundation of principles that include
responsibility to the communities we serve and where we live and work. In 2008, we launched a Corporate Citizenship Initiative, a global
effort to address the environmental, social, economic, and ethical challenges we face in our business. Among the issues we are addressing
are carbon impact, paper specifications and procurement, ethical conduct within our business and among our vendors, and community and
charitable support. For more information, please visit our website: www.wiley.com/go/citizenship.
Copyright © 2011 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or
transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under
Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc. 222 Rosewood Drive, Danvers, MA 01923,
website www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley &
Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201)748–6011, fax (201)748–6008, website http://www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next
academic year. These copies are licensed and may not be sold or transferred to a third party. Upon completion of the review period, please
return the evaluation copy to Wiley. Return instructions and a free of charge return shipping label are available at www.wiley.com/go/
returnlabel. Outside of the United States, please contact your local representative.
—W.J.C.
This page intentionally left blank
BRIEF CONTENTS
Preface xvii
CHAPTER 0
Introduction to Java 1
CHAPTER 1
Object-Oriented Concepts 27
CHAPTER 2
Additional Features of Programming and Java 59
CHAPTER 3
Analysis of Algorithms 105
CHAPTER 4
The Java Collections Framework 133
CHAPTER 5
Recursion 155
CHAPTER 6
Array-Based Lists 233
CHAPTER 7
Linked Lists 267
CHAPTER 8
Stacks and Queues 329
vii
viii BRIEF CONTENTS
CHAPTER 9
Binary Trees 377
CHAPTER 10
Binary Search Trees 401
CHAPTER 11
Sorting 457
CHAPTER 12
Tree Maps and Tree Sets 501
CHAPTER 13
Priority Queues 551
CHAPTER 14
Hashing 599
CHAPTER 15
Graphs, Trees, and Networks 643
APPENDIX 1
Additional Features of the JAVA Collections Framework 701
APPENDIX 2
Mathematical Background 705
APPENDIX 3
Choosing a Data Structure 721
References 725
Index 727
CONTENTS
ix
x CONTENTS
2.8 Overriding the Object Class’s equals 4.2 Some Details of the Java Collections
Method 94 Framework 136
Summary 97 4.2.1 Abstract Classes 137
4.2.2 Parameterized Types 140
Crossword Puzzle 98
4.2.3 The Collection Interface 141
Concept Exercises 99 4.2.4 The List Interface 147
Programming Exercises 100 Summary 150
Programming Project 2.1: An Integrated Web Crossword Puzzle 151
Browser and Search Engine, Part 1 102
Concept Exercises 152
Programming Exercises 152
CHAPTER 3 Programming Project 4.1: Wear a Developer’s Hat
and a User’s Hat 153
Analysis of Algorithms 105
Chapter Objectives 105
3.1 Estimating the Efficiency of Methods 105
3.1.1 Big-O Notation 106
CHAPTER 5
3.1.2 Getting Big-O Estimates Quickly 110
Recursion 155
3.1.3 Big-Omega, Big-Theta and Plain Chapter Objectives 155
English 116 5.1 Introduction 155
3.1.4 Growth Rates 117
5.2 Factorials 156
3.1.5 Trade-Offs 119
5.2.1 Execution Frames 159
3.2 Run-Time Analysis 121
5.3 Decimal to Binary 162
3.2.1 Timing 121
3.2.2 Overview of the Random Class 122 5.4 Towers of Hanoi 167
5.4.1 Analysis of the move Method 177
Summary 126
5.5 Searching an Array 179
Crossword Puzzle 127
5.6 Backtracking 191
Concept Exercises 128
5.6.1 An A-maze-ing Application 195
Programming Exercises 130
5.7 Indirect Recursion 208
Programming Project 3.1: Let’s Make a
5.8 The Cost of Recursion 209
Deal! 131
Summary 210
Crossword Puzzle 211
CHAPTER 4 Concept Exercises 212
Programming Exercises 214
The Java Collections
Framework 133 Programming Project 5.1: Iterative Version of the
Towers of Hanoi 219
Chapter Objectives 133
Programming Project 5.2: Eight Queens 221
4.1 Collections 133
Programming Project 5.3: A Knight’s Tour 222
4.1.1 Collection Classes 134
4.1.2 Storage Structures for Collection Programming Project 5.4: Sudoku 225
Classes 136 Programming Project 5.5: Numbrix 227
CONTENTS xi
CHAPTER 9
Binary Trees 377
Chapter Objectives 377
CHAPTER 11
Sorting 457
9.1 Definition of Binary Tree 377
9.2 Properties of Binary Trees 378 Chapter Objectives 457
9.3 The Binary Tree Theorem 383 11.1 Introduction 457
CONTENTS xiii
CHAPTER 12
Tree Maps and Tree Sets 501 CHAPTER 13
Priority Queues 551
Chapter Objectives 501
12.1 Red-Black Trees 501 Chapter Objectives 551
12.1.1 The Height of a Red Black 13.1 Introduction 551
Tree 503 13.2 The PriorityQueue Class 552
12.2 The Map Interface 504 13.3 Implementation Details of the
12.3 The TreeMap Implementation of the PriorityQueue Class 553
SortedMap Interface 509 13.3.1 Fields and Method Definitions in
12.3.1 The TreeMap Class’s Fields and the PriorityQueue Class 557
Embedded Entry Class 512 13.4 The heapSort Method 567
12.3.2 Method Definitions in the TreeMap 13.4.1 Analysis of heapSort 572
Class 513 13.5 Application: Huffman Codes 573
12.4 Application of the TreeMap Class: a Simple 13.5.1 Huffman Trees 575
Thesaurus 517 13.5.2 Greedy Algorithm Design
12.4.1 Design, Testing, and Implementation Pattern 578
of the Thesaurus Class 518 13.5.3 The Huffman Encoding
12.4.2 Design and Testing of the Project 578
ThesaurusUser Class 521 Summary 590
12.4.3 Implementation of the Crossword Puzzle 591
ThesaurusUser Class 523 Concept Exercises 592
xiv CONTENTS
APPENDIX 1 APPENDIX 3
Additional Features of the JAVA Choosing a Data Structure 721
Collections Framework 701
A3.1 Introduction 721
A1.1 Introduction 701 A3.2 Time-Based Ordering 721
A1.2 Serialization 701 A3.3 Index-Based Ordering 721
A1.3 Fail-Fast Iterators 703 A3.4 Comparison-Based Ordering 722
A3.5 Hash-Based Ordering 723
A3.6 Space Considerations 723
APPENDIX 2 A3.7 The Best Data Structure? 724
Mathematical Background 705
A2.1 Introduction 705
References 725
A2.2 Functions and Sequences 705
A2.3 Sums and Products 706 Index 727
A2.4 Logarithms 707
A2.5 Mathematical Induction 708
A2.6 Induction and Recursion 719
Concept Exercises 719
This page intentionally left blank
PREFACE
This book is intended for an object-oriented course in data structures and algorithms. The implementation
language is Java, and it is assumed that students have taken a first course in programming, not necessarily
in Java. That course should have covered the fundamental statements and data types, as well as arrays.
Chapter 0 supplies the material on Java that is fundamental to the remaining chapters, so it serves as a
review for those with previous experience in Java, and brings Java novices up to speed.
if a wrapper-class element appears where a primitive value is needed, unboxing automatically converts
that element to the corresponding primitive value. Finally, the enhanced for statement—often called a
“for-each” statement—has a sleek structure for iterating through a collection. The net effect of these new
features of Java is to improve productivity by relegating to the compiler many of the “boiler-plate” details
related to casting and iterating.
PEDAGOGICAL FEATURES
This text offers several features that may improve the teaching environment for instructors and the learning
environment for students. Each chapter starts with a list of objectives, and most chapters conclude with
several major programming assignments. Each chapter also has a crossword puzzle, from Crossword
PREFACE xix
Weaver—to help students learn the key words and phrases in an enjoyable setting—and a variety of
exercises. The answers to all of the exercises are available to the instructor.
Each data structure is carefully described, with the specifications for each method given in javadoc
notation. Also, there are examples of how to call the method, and the results of that call. To reinforce
the important aspects of the material and to hone students’ coding skills in preparation for programming
projects, there is a suite of 23 lab experiments. The organization of these labs is described later in this
preface.
SUPPORT MATERIAL
The website for all of the support material is www.wiley.com/college/collins/
That website has links to the following information for students:
• The suite of 23 labs. Lab 0 starts with a brief overview of the lab format.
• The source codes for all classes developed in the text.
• Applets for projects that have a strong visual component.
Additionally, instructors can obtain the following from the website:
• PowerPoint slides for each chapter (approximately 1500 slides).
• Answers to every exercise and lab experiment.
In Chapter 10, we look at binary search trees, including a BinarySearchTree class, and explain the
value of balanced binary search trees. Rotations are introduced as the mechanism by which re-balancing
is accomplished, and AVL trees are offered as examples of balanced binary search trees. An AVLTree
class, as a subclass of BinarySearchTree, is outlined; the crucial methods, fixAfterInsertion and
fixAfterDeletion, are left as programming projects.
Sorting is the theme of Chapter 11. Estimates of the lower bounds for comparison-based sorts are
determined. A few simple sorts are defined, and then we move on to two sort methods provided by the
framework. Quick Sort sorts an array of a primitive type, and Merge Sort works for an array of objects
and for implementations of the List interface. A lab experiment compares all of these sort algorithms on
randomly-generated integers.
The central topic of Chapter 12 is how to use the TreeMap class. A map is a collection in which
each element has a unique key part and also a value part. In the TreeMap implementation of the Map
interface, the elements are stored in a red-black tree, ordered by the elements’ keys. There are labs to
guide students through the details of re-structuring after an insertion or removal. The application consists
of searching a thesaurus for synonyms, and JUnit 4 testing is again illustrated. The TreeSet class has a
TreeMap field in which each element has the same, dummy value-part. The application of the TreeSet
class is a simple spell-checker, which is also thoroughly tested.
Chapter 13 introduces the PriorityQueue class. This class is part of the Java Collections Frame-
work and, like the Stack class and Queue interface in Chapter 8, allows methods that violate the definition
of a priority queue. The class utilizes a heap to provide insertions in constant average time, and removal of
the smallest-valued element in logarithmic worst time. The application is in the area of data compression:
Given a text file, generate a minimal, prefix-free encoding. There is a project assignment to convert the
encoded message back to the original text file.
Chapter 14 investigates hashing. The Java Collections Framework has a HashMap class for elements
that consist of unique-key/value pairs. Basically, the average time for insertion, removal, and searching is
constant! This average speed is exploited in an application (and JUnit 4 tests) to create a simple symbol
table. The Java Collections Framework’s implementation of hashing, using chained hashing, is compared
to open-address hashing.
The most general data structures—graphs, trees, and networks—are presented in Chapter 15. There
are outlines of the essential algorithms: breadth-first traversal, depth-first traversal, finding a minimum
spanning tree, and finding the shortest or longest path between two vertices. The only class developed
is the (directed) Network class, with an adjacency-map implementation. Other classes, such as Undi
rectedGraph and UndirectedNetwork, can be straightforwardly defined as subclasses of Network.
The Traveling Salesperson Problem is investigated in a lab, and there is a programming project to solve
that problem—not necessarily in polynomial time! Another backtracking application is presented, with the
same BackTrack class that was introduced in Chapter 5.
The website includes all programs developed in each chapter, all JUnit 4 tests, and applets, where
appropriate, to animate the concepts presented.
APPENDIXES
Appendix 1 has two additional features of the Java Collections Framework. Each of the collection classes in
the framework is serializable, that is, an instance of the class can be conveniently stored to an output stream,
and the instance can later be re-constituted from an input stream (de-serialization). Framework iterators
are fail-fast: During an iteration through a collection, there should be no insertions into or removals from
xxii PREFACE
the collection except by the iterator. Otherwise, the integrity of that iterator may be compromised, so an
exception will be thrown as soon as the iterator’s unreliability has been established.
Appendix 2 contains the background that will allow students to comprehend the mathematical aspects
of the chapters. Summation notation and the rudimentary properties of logarithms are essential, and the
material on mathematical induction will lead to a deeper appreciation of recursion as well as the analysis
of binary trees.
Appendix 3, “Choosing a Data Structure,” can be viewed as a summary of the eight major data
structures in the book. These collection classes are categorized according to their ordering of elements (for
example, time-based for stacks and queues) and according to their performance of standard operations (for
example, the TreeMap class requires logarithmic-in-n time to search for a key). Table A3.1 summarizes
the summary.
ACKNOWLEDGEMENTS
Joshua Bloch, lead designer of the Java Collections Framework, gave valuable insights on type parameters
and their impact on the Java Collections Framework.
Chun Wai Liew of Lafayette College helped to incorporate JUnit into this edition of the text.
I am indebted to the suggestions and corrections of the reviewers: Dean Hendrix (Auburn University),
Benjamin Kuperman (Oberlin College), Andrew Haas (State University of New York—Albany), Kathy
Liszka (University of Akron), Paul Bladek (Edmonds Community College), Siva Jasthi (Metropolitan State
University), Hashem Anwari (Northern Virginia Community College), Alan Peslak (Nova Southeastern
University), H. K. Dai (Oklahoma State University), Jiang Li (Austin Peay State University), Paul J.
Wagner (University of Wisconsin—Eau Claire), John Mallozzi (Iona College), Robert Goldberg (Queens
College), and Michael Clancy (University of California—Berkeley).
Introduction to Java CHAPTER 0
This is a book about programming: specifically, about understanding and using data structures and
algorithms. The Java Collections Framework has a considerable number of data structures and
algorithms. Subsequent chapters will focus on what the framework is and how to use the framework
in your programs. For this information to make sense to you, you will need to be familiar with certain
aspects of Java that we present in this chapter. All of the material is needed, either for the framework
itself or to enable you to use the framework in your programming projects.
CHAPTER OBJECTIVES
1. Learn (or review) the fundamentals of Java, including classes, objects and messages.
2. Be able to use javadoc in writing method specifications.
3. Incorporate the Scanner class into your programming.
4. Understand the significance of the fact that a copy of the argument is stored in the corre-
sponding parameter when a method is called.
5. Understand the details of arrays and output formatting.
The main method in this program calls another method, println, to produce the following output to the
console window:
Hello, world!
1
Random documents with unrelated
content Scribd suggests to you:
Then the fiddles struck up the air of ‘Sur le pont d’Avignon,’ and
the whole company formed up into circles for the opening Branle.
There was her father, grimacing and leaping like a baboon in a
nightmare, grave magistrates capering like foals, and giving
smacking kisses to their youthful partners, young burghers shouting
the words at the top of their voices. The whole scene seemed to
Madeleine to grow every minute more unreal.
Then the fiddles stopped and the circles broke up into laughing,
breathless groups. A young bourgeois, beplumed and beribboned,
and wearing absurd thick shoes, came up to her, and taking off his
great hat by the crown, instead of, in the manner of ‘les honnêtes
gens,’ by the brim, made her a clumsy bow. He began to ‘galantise’
her. Madeleine wondered if he had learned the art from the elephant
at a fair. She fixed him with her great, still eyes. Then she found
herself forced to lead him out to dance a Pavane. The fiddles were
playing a faint, lonely tune, full of the sadness of light things bound
to a ponderous earth, for these were the days before Lulli had made
dance tunes gay. The beautiful pageant had begun—the Pavane,
proud and preposterous as a peacock or a Spaniard. Then some old
ladies sitting round the room began in thin, cracked voices to sing
according to a bygone fashion, the words of the dance:—
They beat time with their fans, and their eyes filled with tears.
Gradually the song was taken up by the whole room, the words
rising up strong and triumphant:—
When Madeleine awoke next morning, the feeling she had had
over night of being in a dream had by no means left her.
From the street rose the cries of the hawkers:—
Would she get it finished before they arrived? She felt all her
happiness depended on it.
She then made a little bow to the company, and sat down again
on her tabouret, quite undisturbed by the enthusiastic applause that
had followed her recitation.
‘Mademoiselle,’ began Godeau solemnly, ‘words fail me, to use the
delicious expression of Saint Amant, with which to praise your
ravishing verses as they deserve. But if the Abbé Ménage were here,
I think he might ask you if the qui in ... let me see ... the sixth line,
refers to the bourse or to the act of pricking your finger. Because if,
as I imagine, it is to the latter, the laws of our language demand the
insertion of a ce before the qui, while the unwritten laws of universal
experience assert that the action of pricking one’s finger should be
called bête not pas bête. We writers must be prepared for this sort
of ignoble criticism.’
‘Of course the qui refers to bourse,’ said Madame de Montausier,
for the child was looking bewildered. ‘You will pardon me but what
an exceeding foolish question from a Member of the Academy! It
was bête to prick one’s finger, but who, with justice, could call bête a
bourse of most quaint and excellent design? Is it not so, ma chatte?’
The child nodded solemnly, and Monsieur de Grasse was profuse in
his apologies for his stupidity.
Madeleine had noticed that the only member of the company,
except herself, who had not been entranced by this performance,
was Mademoiselle de Scudéry. Though she smiled the whole time,
and was profuse in her compliments, yet she was evidently bored.
Instead of pleasing Madeleine, this shocked her, it also made her
rather despise her, for being out of it.
She turned to Montausier and said timidly:—
‘I should dearly love to see Mademoiselle votre fille and the
Cardinal’s baby niece together. They would make a delicious pair.’
But Montausier either really did not hear, or pretended not to, and
Madeleine had the horrible embarrassment of speaking to air.
‘Who is that demoiselle?’ the child suddenly cried in a shrill voice,
looking at Madeleine.
‘That is Mademoiselle Hoqueville, my love.’
‘Hoqueville! what a droll name!’ and she went into peals of shrill
laughter. The grandparents and mother of the child smiled
apologetically at Madeleine, but she, in agony at being humiliated,
as she considered, before Mademoiselle de Scudéry, tried to improve
matters by looking haughty and angry. However, this remark
reminded Madame de Rambouillet of Madeleine’s existence, and she
exclaimed:—
‘Oh! Mademoiselle Hoqueville, you have, as yet, seen naught of
the hôtel. Marie-Julie, my love, go and say bon-jour to that lady and
ask her if she will accompany you to the salle bleue.’
The child obediently went over to Madeleine, curtseyed, and held
out her hand. Madeleine was not certain whether she ought to
curtsey back or merely bow without rising from the chair. She
compromised in a cross between the two, which made her feel
extremely foolish. On being asked if she would like to see la salle
bleue, she had to say yes, and followed the child out of the room.
She followed her through a little cabinet, and then they were in
the famous room, sung by so many poets, the scene of so many gay
and brilliant happenings.
Madeleine’s first feeling was one of intense relief at being freed
from the strain of the bedroom, then, as it were, she galvanised into
activity her demand upon life, and felt in despair at losing even a
few moments of Mademoiselle de Scudéry’s company. The child
walked on in front humming a little tune to herself. Madeleine felt
she must pull herself together, and make friends with her.
‘What rare and skilful verses those were you recited to us,’ she
began, her voice harshly breaking the silence of the huge room. The
child looked at her out of her crab-eyes, pursed up her mouth, and
went on humming.
‘Do you dearly love your little dog?’
‘Haven’t got one.’ This was startling.
‘But you made mention of one in your poem,’ said Madeleine in an
aggrieved tone.
The child screamed with scornful laughter:—
‘She isn’t mine, she’s Aunt Angélique’s!’ she cried, and looked at
Madeleine as if she must be mad for having made such a mistake.
There was another pause. Madeleine sighed wearily and went to
look at the famous tapestry, the child followed her.
Its design consisted of groups of small pastoral figures disporting
themselves in a blue Arcady. In one group there was a shepherdess
sitting on a rustic bench, surrounded by shepherds; a nymph was
offering her a basket of flowers. The child pointed to the
shepherdess: ‘That is my grandmother, and that is me bringing her
flowers, and that is my father, and that is Monsieur Sarrasin, and
that is my dear Maître Claude!’ ... This was better. Madeleine made a
violent effort to be suitably fantastic.
‘It may be when you are asleep you do in truth become that
nymph and live in the tapestry.’ The child stared at her, frowned, and
continued her catalogue:—
‘And that is my mother, and that is Aunt Angélique, and that is
Madame de Longueville, and that is Madame de Sablé, and that is
Monsieur de la Rochefoucauld, and that is my little friend
Mademoiselle de Sévigné,’ and so on.
When she had been through the list of her acquaintances, she
wandered off and began to play with a box of ivory puzzles.
Madeleine, in a final attempt to ingratiate herself, found for her
some of the missing pieces, at which her mouth began to tremble,
and Madeleine realised that all the pleasure lay in doing it by herself,
so she left her, and with a heavy heart crept back to the bedroom.
She found Madame Cornuel and Mademoiselle Legendre preparing
to go, and supposing they had already said good-bye, solemnly
curtseyed to all the company in turn. They responded with great
friendliness and kindness, but she suddenly noticed Madame Cornuel
exchanging glances with her step-daughter, and realised in a flash
that by making her adieux she had been guilty of a provincialism.
She smiled grimly to herself. What did it matter?
Madame Cornuel dropped her in the rue Saint-Honoré, and she
walked quietly home.
She had not exchanged a single word with Mademoiselle de
Scudéry.
CHAPTER X
AFTERWARDS