Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (10 votes)
34 views

Get (eBook PDF) Data Structures and Other Objects Using Java 4th Edition free all chapters

Ebookluna.com offers seamless downloads of various eBooks across multiple genres, including several editions of Java programming and data structures. The site features instant digital products in formats such as PDF, ePub, and MOBI, allowing users to choose the format that best suits their needs. Additionally, the document outlines a structured approach to teaching data structures and Java programming, emphasizing the importance of understanding data types, object-oriented programming, and advanced topics like recursion and sorting.

Uploaded by

brigjapropst
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (10 votes)
34 views

Get (eBook PDF) Data Structures and Other Objects Using Java 4th Edition free all chapters

Ebookluna.com offers seamless downloads of various eBooks across multiple genres, including several editions of Java programming and data structures. The site features instant digital products in formats such as PDF, ePub, and MOBI, allowing users to choose the format that best suits their needs. Additionally, the document outlines a structured approach to teaching data structures and Java programming, emphasizing the importance of understanding data types, object-oriented programming, and advanced topics like recursion and sorting.

Uploaded by

brigjapropst
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Experience Seamless Full Ebook Downloads for Every Genre at ebookluna.

com

(eBook PDF) Data Structures and Other Objects


Using Java 4th Edition

https://ebookluna.com/product/ebook-pdf-data-structures-and-
other-objects-using-java-4th-edition/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://ebookluna.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

(eBook PDF) Data Structures and Problem Solving Using Java


4th Edition

https://ebookluna.com/product/ebook-pdf-data-structures-and-problem-
solving-using-java-4th-edition/

ebookluna.com

(eBook PDF) Data Structures and Abstractions with Java 4th


Edition

https://ebookluna.com/product/ebook-pdf-data-structures-and-
abstractions-with-java-4th-edition/

ebookluna.com

(eBook PDF) Data Structures and Abstractions with Java 4th


Global Edition

https://ebookluna.com/product/ebook-pdf-data-structures-and-
abstractions-with-java-4th-global-edition/

ebookluna.com

(eBook PDF) Starting Out with Java: From Control


Structures through Data Structures 4th Edition

https://ebookluna.com/product/ebook-pdf-starting-out-with-java-from-
control-structures-through-data-structures-4th-edition/

ebookluna.com
Data Structures and Abstractions with Java 5th Edition
(eBook PDF)

https://ebookluna.com/product/data-structures-and-abstractions-with-
java-5th-edition-ebook-pdf/

ebookluna.com

(eBook PDF) Starting Out with Java: From Control


Structures through Objects, 7th Edition

https://ebookluna.com/product/ebook-pdf-starting-out-with-java-from-
control-structures-through-objects-7th-edition/

ebookluna.com

(eBook PDF) Starting Out with Java: From Control


Structures through Data Structures 3rd Edition

https://ebookluna.com/product/ebook-pdf-starting-out-with-java-from-
control-structures-through-data-structures-3rd-edition/

ebookluna.com

(eBook PDF) Introduction to JAVA Programming and Data


Structures Comprehensive Version 11

https://ebookluna.com/product/ebook-pdf-introduction-to-java-
programming-and-data-structures-comprehensive-version-11/

ebookluna.com

(eBook PDF) Java Foundations: Introduction to Program


Design and Data Structures 5th Edition

https://ebookluna.com/product/ebook-pdf-java-foundations-introduction-
to-program-design-and-data-structures-5th-edition/

ebookluna.com
Preface vii

each method is presented along with a precondition/postcondition contract that


completely specifies the behavior of the method. At this level, it’s important for
the students to realize that the specification is not tied to any particular choice of
implementation techniques. In fact, this same specification may be used several
times for several different implementations of the same data type.

Step 3: Use the Data Type. With the specification in place, students can write
small applications or applets to show the data type in use. These applications are
based solely on the data type’s specification because we still have not tied down
the implementation.

Step 4: Select Appropriate Data Structures and Proceed to Design and


Implement the Data Type. With a good abstract understanding of the data
type, we can select an appropriate data structure, such as an array, a linked list of
nodes, or a binary tree of nodes. For many of our data types, a first design and
implementation will select a simple approach, such as an array. Later, we will
redesign and reimplement the same data type with a more complicated underly-
ing structure.
Because we are using Java classes, an implementation of a data type will have
the selected data structures (arrays, references to other objects, etc.) as private
instance variables of the class. In my own teaching, I stress the necessity for a
clear understanding of the rules that relate the private instance variables to the
abstract notion of the data type. I require each student to write these rules in clear
English sentences that are called the invariant of the abstract data type. Once the
invariant is written, students can proceed to implementing various methods. The
invariant helps in writing correct methods because of two facts: (a) Each method
(except the constructors) knows that the invariant is true when the method begins
its work; and (b) each method is responsible for ensuring that the invariant is
again true when the method finishes.

Step 5: Analyze the Implementation. Each implementation can be analyzed


for correctness, flexibility, and time analysis of the operations (using big-O
notation). Students have a particularly strong opportunity for these analyses
when the same data type has been implemented in several different ways.

Where Will the Students Be at the End of the Course?


At the end of our course, students understand the data types inside out. They
know how to use the data types and how to implement them in several ways.
They know the practical effects of the different implementation choices. The
students can reason about efficiency with a big-O analysis and can argue for the
correctness of their implementations by referring to the invariant of the ADT.
viii Preface

the data types in One of the lasting effects of the course is the specification, design, and imple-
this book are mentation experience. The improved ability to reason about programs is also
cut-down important. But perhaps most important of all is the exposure to classes that are
versions of the easily used in many situations. The students no longer have to write everything
Java Class from scratch. We tell our students that someday they will be thinking about a
Libraries problem, and they will suddenly realize that a large chunk of the work can be
done with a bag, a stack, a queue, or some such. And this large chunk of work is
work that they won’t have to do. Instead, they will pull out the bag or stack or
queue that they wrote this semester—using it with no modifications. Or, more
likely, they will use the familiar data type from a library of standard data types,
such as the proposed Java Class Libraries. In fact, the behavior of some data
types in this text is a cut-down version of the JCL, so when students take the step
to the real JCL, they will be on familiar ground—from the standpoint of how to
use the class and also having a knowledge of the considerations that went into
building the class.

Other Foundational Topics


Throughout the course, we also lay a foundation for other aspects of “real pro-
gramming,” with coverage of the following topics beyond the basic data struc-
tures material.

Object-Oriented Programming. The foundations of object-oriented pro-


gramming are laid by giving students a strong understanding of Java classes.
The important aspects of classes are covered early: the notion of a method, the
separation into private and public members, the purpose of constructors, and a
small exposure to cloning and testing for equality. This is primarily covered in
Chapter 2, some of which can be skipped by students with a good exposure to
Java classes in the CS1 course.
Further aspects of classes are introduced when the classes first use dynamic
arrays (Chapter 3). At this point, the need for a more sophisticated clone method
is explained. Teaching this OOP method with the first use of dynamic memory
has the effect of giving the students a concrete picture of how an instance vari-
able is used as a reference to a dynamic object such as an array.
Conceptually, the largest innovation of OOP is the software reuse that occurs
via inheritance. There are certainly opportunities for introducing inheritance
right from the start of a data structures course (such as implementing a set class
as a descendant of a bag class). However, an early introduction may also result
in students juggling too many new concepts at once, resulting in a weaker under-
standing of the fundamental data structures. Therefore, in my own course, I intro-
duce inheritance at the end as a vision of things to come. But the introduction to
inheritance (Sections 13.1 and 13.2) could be covered as soon as classes are
understood. With this in mind, some instructors may wish to cover Chapter 13
earlier, just before stacks and queues, so that stacks and queues can be derived
from another class.
Preface ix

Another alternative is to identify students who already know the basics of


classes. These students can carry out an inheritance project (such as the ecosys-
tem of Section 13.3), while the rest of the students first learn about classes.

Java Objects. The Java Object type lies at the base of all the other Java
types—or at least almost all the other types. The eight primitive types are not
Java objects, and for many students, the CS1 work has been primarily with the
eight primitive types. Because of this, the first few data structures are collec-
tions of primitive values, such as a bag of integers or a sequence of double num-
bers.

Iterators. Iterators are an important part of the Java Class Libraries, allowing
a programmer to easily step through the elements in a collection class. The
Iteratable interface is introduced in Chapter 5. Throughout the rest of the
text, iterators are not directly used, although they provide a good opportunity for
programming projects, such as using a stack to implement an iterator for a
binary search tree (Chapter 9).

Recursion. First-semester courses often introduce students to recursion. But


many of the first-semester examples are tail recursion, where the final act of the
method is the recursive call. This may have given students a misleading impres-
sion that recursion is nothing more than a loop. Because of this, I prefer to avoid
early use of tail recursion in a second-semester course.
So, in our second-semester course, we emphasize recursive solutions that use
more than tail recursion. The recursion chapter provides four examples along
these lines. Two of the examples—generating random fractals and traversing a
maze—are big hits with the students. The fractal example runs as a graphical
applet, and although the maze example is text based, an adventurous student can
convert it to a graphical applet. These recursion examples (Chapter 8) appear just
before trees (Chapter 9) since it is within recursive tree algorithms that recursion
becomes vital. However, instructors who desire more emphasis on recursion can
move that topic forward, even before Chapter 2.
In a course that has time for advanced tree projects (Chapter 10), we analyze
the recursive tree algorithms, explaining the importance of keeping the trees
balanced—both to improve worst-case performance and to avoid potential
execution stack overflow.

Searching and Sorting. Chapters 11 and 12 provide fundamental coverage of


searching and sorting algorithms. The searching chapter reviews binary search
of an ordered array, which many students will have seen before. Hash tables are
also introduced in the search chapter by implementing a version of the JCL hash
table and also a second hash table that uses chaining instead of open addressing.
The sorting chapter reviews simple quadratic sorting methods, but the majority
of the chapter focuses on faster algorithms: the recursive merge sort (with
worst-case time of O(n log n)), Tony Hoare’s recursive quicksort (with average-
time O(n log n)), and the tree-based heapsort (with worst-case time of O(n log n)).
x Preface

Advanced Projects, Including Concurrency


The text offers good opportunities for optional projects that can be undertaken
by a more advanced class or by students with a stronger background in a large
class. Particular advanced projects include the following:
• Interactive applet-based test programs for any of the data structures (out-
lined in Appendix I).
• Implementing an iterator for the sequence class (see Chapter 5 Program-
ming Projects).
• Writing a deep clone method for a collection class (see Chapter 5 Pro-
gramming Projects).
• Writing an applet version of an application program (such as the maze tra-
versal in Section 8.2 or the ecosystem in Section 13.3).
• Using a stack to build an iterator for the binary search tree (see Chapter 9
Programming Projects).
• A priority queue implemented as an array of ordinary queues (Section
7.4) or implemented using a heap (Section 10.1).
• A set class implemented with B-trees (Section 10.2). I have made a partic-
ular effort on this project to provide sufficient information for students to
implement the class without need of another text. Advanced students have
successfully completed this project as independent work.
• Projects to support concurrent sorting in the final section of Chapter 12.
• An inheritance project, such as the ecosystem of Section 13.3.
• A graph class and associated graph algorithms in Chapter 14. This is
another case in which advanced students may do work on their own.

Java Language Versions


All the source code in the book has been tested to work correctly with Java 2
Standard Edition Version 7.0, including new features such as generics and new
concurrency support. Information on all of the Java products from Sun Micro-
systems is available at http://java.sun.com/products/index.html.
Flexibility of Topic Ordering
This book was written to give instructors latitude in reordering the material to
meet the specific background of students or to add early emphasis to selected
topics. The dependencies among the chapters are shown on the next page. A line
joining two boxes indicates that the upper box should be covered before the
lower box.
Here are some suggested orderings of the material:
Typical Course. Start with Chapters 1–9, skipping parts of Chapter 2 if the
students have a prior background in Java classes. Most chapters can be covered
in a week, but you may want more time for Chapter 4 (linked lists), Chapter 8
(recursion), or Chapter 9 (trees). Typically, I cover the material in 13 weeks,
Preface xi

Chapter Dependencies

At the start of the course, students should be comfortable writing


application programs and using arrays in Java.

Chapter 1
Introduction

Chapters 2–3
Classes
Reference variables
Collection classes Chapter 8
Recursion
Chapter 2 can be skipped by students
with a good background in Java classes.

Section 11.1
Chapter 4
Binary search
Linked lists
Chapter 13
Extended classes
Sections 5.1–5.4 Sec. 11.2–11.3
Generic programming Hash tables
(Also requires
Chapter 5)
Sections 5.5–5.7 Chapter 6
The Java API Stacks
Chapter 12
Iterators Sorting
Java collections (Heapsort also
Java maps Chapter 7 Chapter 9
needs Section
Queues Trees
10.1)

Section 10.1 Section 10.2 Section 10.3


Heaps B-trees Java trees

The shaded boxes provide


Section 10.4 Chapter 14
good opportunities for
Detailed tree analysis Graphs
advanced work.
xii Preface

including time for exams and extra time for linked lists and trees. Remaining
weeks can be spent on a tree project from Chapter 10 or on binary search (Sec-
tion 11.1) and sorting (Chapter 12).
Heavy OOP Emphasis. If students will cover sorting and searching else-
where, then there is time for a heavier emphasis on object-oriented program-
ming. The first three chapters are covered in detail, and then derived classes
(Section 13.1) are introduced. At this point, students can do an interesting OOP
project, perhaps based on the ecosystem of Section 13.3. The basic data struc-
tures (Chapters 4 –7) are then covered, with the queue implemented as a derived
class (Section 13.4). Finish up with recursion (Chapter 8) and trees (Chapter 9),
placing special emphasis on recursive methods.
Accelerated Course. Assign the first three chapters as independent reading in
the first week and start with Chapter 4 (linked lists). This will leave two to three
extra weeks at the end of the term so that students can spend more time on
searching, sorting, and the advanced topics (shaded in the chapter dependencies
list).
I also have taught the course with further acceleration by spending no lecture
time on stacks and queues (but assigning those chapters as reading).
Early Recursion / Early Sorting. One to three weeks may be spent at the
start of class on recursive thinking. The first reading will then be Chapters 1 and
8, perhaps supplemented by additional recursive projects.
If the recursion is covered early, you may also proceed to cover binary search
(Section 11.1) and most of the sorting algorithms (Chapter 12) before introduc-
ing collection classes.

Supplements Via the Internet


The following materials are available to all readers of this text at cssup-
port.pearsoncmg.com (or alternatively at www.cs.colorado.edu/~main/
dsoj.html):
• Source code
• Errata
In addition, the following supplements are available to qualified instructors.
Visit Addison-Wesley’s Instructor Resource Center (www.aw.com/irc) or con-
tact your local Addison-Wesley representative for access to these:
• PowerPoint® presentations
• Exam questions
• Solutions to selected programming projects
• Speaker notes
• Sample assignments
• Suggested syllabi
Preface xiii

Acknowledgments
This book grew from joint work with Walter Savitch, who continues to be an
ever-present and enthusiastic supporter, colleague, and friend. My students from
the University of Colorado at Boulder serve to provide inspiration and joy at
every turn, particularly the spring seminars in Natural Computing and Ideas in
Computing. During the past few years, the book has also been extensively
reviewed by J.D. Baker, Philip Barry, Arthur Crummer, Herbert Dershem, Greg
Dobbins, Zoran Duric, Dan Grecu, Scott Grissom, Bob Holloway, Rod Howell,
Danny Krizanc, Ran Libeskind-Hadas, Meiliu Lu, Catherine Matthews, Robert
Moll, Robert Pastel, Don Slater, Ryan Stansifer, Deborah Trytten, and John
Wegis. I thank these colleagues for their excellent critique and their encourage-
ment.
At Addison-Wesley, I thank Tracy Dunkelberger, Michael Hirsch, Bob
Engelhardt, and Stephanie Sellinger, who have provided continual support and
knowledgeable advice.
I also thank my friends and colleagues who have given me daily
encouragement and friendship during the writing of this fourth edition: Andrzej
Ehrenfeucht, Marga Powell, Grzegorz Rozenberg, and Allison Thompson-
Brown, and always my family: Janet, Tim, Hannah, Michelle, and Paul.

Michael Main (main@colorado.edu)


Boulder, Colorado
xiv Preface

Chapter List

Chapter 1 THE PHASES OF SOFTWARE DEVELOPMENT 1


Chapter 2 JAVA CLASSES AND INFORMATION HIDING 38
Chapter 3 COLLECTION CLASSES 103
Chapter 4 LINKED LISTS 175
Chapter 5 GENERIC PROGRAMMING 251
Chapter 6 STACKS 315
Chapter 7 QUEUES 360
Chapter 8 RECURSIVE THINKING 409
Chapter 9 TREES 453
Chapter 10 TREE PROJECTS 520
Chapter 11 SEARCHING 567
Chapter 12 SORTING 614
Chapter 13 SOFTWARE REUSE WITH EXTENDED CLASSES 675
Chapter 14 GRAPHS 728

APPENDIXES 775
INDEX 815
Contents xv

Contents
CHAPTER 1 THE PHASES OF SOFTWARE DEVELOPMENT 1
1.1 Specification, Design, Implementation 4
Design Technique: Decomposing the Problem 5
How to Write a Specification for a Java Method 6
Pitfall: Throw an Exception to Indicate a Failed Precondition 9
Temperature Conversion: Implementation 10
Programming Tip: Use Javadoc to Write Specifications 13
Programming Tip: Use Final Variables to Improve Clarity 13
Programming Tip: Make Exception Messages Informative 14
Programming Tip: Format Output with System.out.printf 14
Self-Test Exercises for Section 1.1 15
1.2 Running Time Analysis 16
The Stair-Counting Problem 16
Big-O Notation 21
Time Analysis of Java Methods 23
Worst-Case, Average-Case, and Best-Case Analyses 25
Self-Test Exercises for Section 1.2 26
1.3 Testing and Debugging 26
Choosing Test Data 27
Boundary Values 27
Fully Exercising Code 28
Pitfall: Avoid Impulsive Changes 29
Using a Debugger 29
Assert Statements 29
Turning Assert Statements On and Off 30
Programming Tip: Use a Separate Method for Complex Assertions 32
Pitfall: Avoid Using Assertions to Check Preconditions 34
Static Checking Tools 34
Self-Test Exercises for Section 1.3 34
Chapter Summary 35
Solutions to Self-Test Exercises 36

CHAPTER 2 JAVA CLASSES AND INFORMATION HIDING 38


2.1 Classes and Their Members 40
Defining a New Class 41
Instance Variables 41
Constructors 42
No-Arguments Constructors 43
Methods 43
Accessor Methods 44
Programming Tip: Four Reasons to Implement Accessor Methods 44
Pitfall: Division Throws Away the Fractional Part 45
Programming Tip: Use the Boolean Type for True or False Values 46
Modification Methods 46
Pitfall: Potential Arithmetic Overflows 48
Complete Definition of Throttle.java 48
Methods May Activate Other Methods 51
Self-Test Exercises for Section 2.1 51
xvi Contents

2.2 Using a Class 52


Creating and Using Objects 52
A Program with Several Throttle Objects 53
Null References 54
NullPointerException 55
Assignment Statements with Reference Variables 55
Clones 58
Testing for Equality 58
Terminology Controversy: “The Throttle That t Refers To” 59
Self-Test Exercises for Section 2.2 59
2.3 Packages 60
Declaring a Package 60
The Import Statement to Use a Package 63
The JCL Packages 63
More about Public, Private, and Package Access 63
Self-Test Exercises for Section 2.3 65
2.4 Parameters, Equals Methods, and Clones 65
The Location Class 66
Static Methods 72
Parameters That Are Objects 73
Methods May Access Private Instance Variables of Objects in Their Own Class 74
The Return Value of a Method May Be an Object 75
Programming Tip: How to Choose the Names of Methods 76
Java’s Object Type 77
Using and Implementing an Equals Method 77
Pitfall: ClassCastException 80
Every Class Has an Equals Method 80
Using and Implementing a Clone Method 81
Pitfall: Older Java Code Requires a Typecast for Clones 81
Programming Tip: Always Use super.clone for Your Clone Method 85
Programming Tip: When to Throw a Runtime Exception 85
A Demonstration Program for the Location Class 85
What Happens When a Parameter Is Changed Within a Method? 86
Self-Test Exercises for Section 2.4 89
2.5 The Java Class Libraries 90
Chapter Summary 92
Solutions to Self-Test Exercises 93
Programming Projects 95
Contents xvii

CHAPTER 3 COLLECTION CLASSES 103


3.1 A Review of Java Arrays 104
Pitfall: Exceptions That Arise from Arrays 106
The Length of an Array 106
Assignment Statements with Arrays 106
Clones of Arrays 107
The Arrays Utility Class 108
Array Parameters 110
Programming Tip: Enhanced For-Loops for Arrays 111
Self-Test Exercises for Section 3.1 112
3.2 An ADT for a Bag of Integers 113
The Bag ADT—Specification 114
OutOfMemoryError and Other Limitations for Collection Classes 118
The IntArrayBag Class—Specification 118
The IntArrayBag Class—Demonstration Program 122
The IntArrayBag Class—Design 125
The Invariant of an ADT 126
The IntArrayBag ADT—Implementation 127
Programming Tip: Cloning a Class That Contains an Array 136
The Bag ADT—Putting the Pieces Together 137
Programming Tip: Document the ADT Invariant in the Implementation File 141
The Bag ADT—Testing 141
Pitfall: An Object Can Be an Argument to Its Own Method 142
The Bag ADT—Analysis 142
Self-Test Exercises for Section 3.2 144
3.3 Programming Project: The Sequence ADT 145
The Sequence ADT—Specification 146
The Sequence ADT—Documentation 150
The Sequence ADT—Design 150
The Sequence ADT—Pseudocode for the Implementation 156
Self-Test Exercises for Section 3.3 158
3.4 Programming Project: The Polynomial 159
Self-Test Exercises for Section 3.4 162
3.5 The Java HashSet and Iterators 162
The HashSet Class 162
Some of the HashSet Members 162
Iterators 163
Pitfall: Do Not Access an Iterator’s next Item When hasNext Is False 164
Pitfall: Changing a Container Object Can Invalidate Its Iterator 164
Invalid Iterators 164
Self-Test Exercises for Section 3.5 165
Chapter Summary 165
Solutions to Self-Test Exercises 166
Programming Projects 169
xviii Contents

CHAPTER 4 LINKED LISTS 175


4.1 Fundamentals of Linked Lists 176
Declaring a Class for Nodes 177
Head Nodes, Tail Nodes 177
The Null Reference 178
Pitfall: NullPointerExceptions with Linked Lists 179
Self-Test Exercises for Section 4.1 179
4.2 Methods for Manipulating Nodes 179
Constructor for the Node Class 180
Getting and Setting the Data and Link of a Node 180
Public Versus Private Instance Variables 181
Adding a New Node at the Head of a Linked List 182
Removing a Node from the Head of a Linked List 183
Adding a New Node That Is Not at the Head 185
Removing a Node That Is Not at the Head 188
Pitfall: NullPointerExceptions with removeNodeAfter 191
Self-Test Exercises for Section 4.2 191
4.3 Manipulating an Entire Linked List 192
Computing the Length of a Linked List 193
Programming Tip: How to Traverse a Linked List 196
Pitfall: Forgetting to Test the Empty List 197
Searching for an Element in a Linked List 197
Finding a Node by Its Position in a Linked List 198
Copying a Linked List 200
A Second Copy Method, Returning Both Head and Tail References 204
Programming Tip: A Method Can Return an Array 205
Copying Part of a Linked List 206
Using Linked Lists 207
Self-Test Exercises for Section 4.3 214
4.4 The Bag ADT with a Linked List 215
Our Second Bag—Specification 215
The grab Method 219
Our Second Bag—Class Declaration 219
The Second Bag—Implementation 220
Programming Tip: Cloning a Class That Contains a Linked List 223
Programming Tip: How to Choose between Different Approaches 225
The Second Bag—Putting the Pieces Together 229
Self-Test Exercises for Section 4.4 232
4.5 Programming Project: The Sequence ADT with a Linked List 232
The Revised Sequence ADT—Design Suggestions 232
The Revised Sequence ADT—Clone Method 235
Self-Test Exercises for Section 4.5 238
4.6 Beyond Simple Linked Lists 239
Arrays Versus Linked Lists and Doubly Linked Lists 239
Dummy Nodes 240
Java’s List Classes 241
ListIterators 242
Making the Decision 243
Self-Test Exercises for Section 4.6 244
Chapter Summary 244
Solutions to Self-Test Exercises 245
Programming Projects 248
Contents xix

CHAPTER 5 GENERIC PROGRAMMING 251


5.1 Java’s Object Type and Wrapper Classes 252
Widening Conversions 253
Narrowing Conversions 254
Wrapper Classes 256
Autoboxing and Auto-Unboxing Conversions 256
Advantages and Disadvantages of Wrapper Objects 257
Self-Test Exercises for Section 5.1 257
5.2 Object Methods and Generic Methods 258
Object Methods 259
Generic Methods 259
Pitfall: Generic Method Restrictions 260
Self-Test Exercises for Section 5.2 261
5.3 Generic Classes 262
Writing a Generic Class 262
Using a Generic Class 262
Pitfall: Generic Class Restrictions 263
Details for Implementing a Generic Class 263
Creating an Array to Hold Elements of the Unknown Type 263
Retrieving E Objects from the Array 264
Warnings in Generic Code 264
Programming Tip: Suppressing Unchecked Warnings 265
Using ArrayBag as the Type of a Parameter or Return Value 266
Counting the Occurrences of an Object 266
The Collection Is Really a Collection of References to Objects 267
Set Unused References to Null 269
Steps for Converting a Collection Class to a Generic Class 269
Deep Clones for Collection Classes 271
Using the Bag of Objects 279
Details of the Story-Writing Program 282
Self-Test Exercises for Section 5.3 282
5.4 Generic Nodes 283
Nodes That Contain Object Data 283
Pitfall: Misuse of the equals Method 283
Other Collections That Use Linked Lists 285
Self-Test Exercises for Section 5.4 285
5.5 Interfaces and Iterators 286
Interfaces 286
How to Write a Class That Implements an Interface 287
Generic Interfaces and the Iterable Interface 287
How to Write a Generic Class That Implements a Generic Interface 288
The Lister Class 289
Pitfall: Don’t Change a List While an Iterator Is Being Used 291
The Comparable Generic Interface 292
Parameters That Use Interfaces 293
Using instanceof to Test Whether a Class Implements an Interface 294
The Cloneable Interface 295
Self-Test Exercises for Section 5.5 295
xx Contents

5.6 A Generic Bag Class That Implements the Iterable Interface (Optional Section) 296
Programming Tip: Enhanced For-Loops for the Iterable Interface 297
Implementing a Bag of Objects Using a Linked List and an Iterator 298
Programming Tip: External Iterators Versus Internal Iterators 298
Summary of the Four Bag Implementations 299
Self-Test Exercises for Section 5.6 299
5.7 The Java Collection Interface and Map Interface (Optional Section) 300
The Collection Interface 300
The Map Interface and the TreeMap Class 300
The TreeMap Class 302
The Word Counting Program 305
Self-Test Exercises for Section 5.7 306
Chapter Summary 309
Solutions to Self-Test Exercises 310
Programming Projects 312

CHAPTER 6 STACKS 315


6.1 Introduction to Stacks 316
The Stack Class—Specification 317
We Will Implement a Generic Stack 319
Programming Example: Reversing a Word 319
Self-Test Exercises for Section 6.1 320
6.2 Stack Applications 320
Programming Example: Balanced Parentheses 320
Programming Tip: The Switch Statement 324
Evaluating Arithmetic Expressions 325
Evaluating Arithmetic Expressions—Specification 325
Evaluating Arithmetic Expressions—Design 325
Implementation of the Evaluate Method 329
Evaluating Arithmetic Expressions—Testing and Analysis 333
Evaluating Arithmetic Expressions—Enhancements 334
Self-Test Exercises for Section 6.2 334
6.3 Implementations of the Stack ADT 335
Array Implementation of a Stack 335
Linked List Implementation of a Stack 341
Self-Test Exercises for Section 6.3 344
6.4 More Complex Stack Applications 345
Evaluating Postfix Expressions 345
Translating Infix to Postfix Notation 348
Using Precedence Rules in the Infix Expression 350
Correctness of the Conversion from Infix to Postfix 353
Self-Test Exercises for Section 6.4 354
Chapter Summary 354
Solutions to Self-Test Exercises 355
Programming Projects 356
Contents xxi

CHAPTER 7 QUEUES 360


7.1 Introduction to Queues 361
The Queue Class 362
Uses for Queues 364
Self-Test Exercises for Section 7.1 365
7.2 Queue Applications 365
Java Queues 365
Programming Example: Palindromes 366
Programming Example: Car Wash Simulation 369
Car Wash Simulation—Specification 369
Car Wash Simulation—Design 369
Car Wash Simulation—Implementing the Car Wash Classes 374
Car Wash Simulation—Implementing the Simulation Method 375
Self-Test Exercises for Section 7.2 375
7.3 Implementations of the Queue Class 383
Array Implementation of a Queue 383
Programming Tip: Use Helper Methods to Improve Clarity 386
Linked List Implementation of a Queue 393
Pitfall: Forgetting Which End Is Which 398
Self-Test Exercises for Section 7.3 398
7.4 Deques and Priority Queues (Optional Section) 399
Double-Ended Queues 399
Priority Queues 400
Priority Queue ADT—Specification 400
Priority Queue Class—An Implementation That Uses an Ordinary Queue 402
Priority Queue ADT—A Direct Implementation 403
Java’s Priority Queue 403
Self-Test Exercises for Section 7.4 404
Chapter Summary 404
Solutions to Self-Test Exercises 404
Programming Projects 406

CHAPTER 8 RECURSIVE THINKING 409


8.1 Recursive Methods 410
Tracing Recursive Calls 413
Programming Example: An Extension of writeVertical 413
A Closer Look at Recursion 415
General Form of a Successful Recursive Method 418
Self-Test Exercises for Section 8.1 419
8.2 Studies of Recursion: Fractals and Mazes 420
Programming Example: Generating Random Fractals 420
A Method for Generating Random Fractals—Specification 421
The Stopping Case for Generating a Random Fractal 426
Putting the Random Fractal Method in an Applet 426
Programming Example: Traversing a Maze 429
Traversing a Maze—Specification 429
Traversing a Maze—Design 432
Traversing a Maze—Implementation 433
The Recursive Pattern of Exhaustive Search with Backtracking 435
Programming Example: The Teddy Bear Game 437
Self-Test Exercises for Section 8.2 437
xxii Contents

8.3 Reasoning about Recursion 439


How to Ensure That There Is No Infinite Recursion in the General Case 442
Inductive Reasoning about the Correctness of a Recursive Method 444
Self-Test Exercises for Section 8.3 445
Chapter Summary 446
Solutions to Self-Test Exercises 446
Programming Projects 448

CHAPTER 9 TREES 453


9.1 Introduction to Trees 454
Binary Trees 454
Binary Taxonomy Trees 457
More Than Two Children 458
Self-Test Exercises for Section 9.1 459
9.2 Tree Representations 459
Array Representation of Complete Binary Trees 459
Representing a Binary Tree with a Generic Class for Nodes 462
Self-Test Exercises for Section 9.2 464
9.3 A Class for Binary Tree Nodes 464
Programming Example: Animal Guessing 473
Animal-Guessing Program—Design and Implementation 475
Animal-Guessing Program—Improvements 481
Self-Test Exercises for Section 9.3 481
9.4 Tree Traversals 484
Traversals of Binary Trees 484
Printing a Tree with an Indentation to Show the Depths 488
BTNode, IntBTNode, and Other Classes 497
Self-Test Exercises for Section 9.4 497
9.5 Binary Search Trees 498
The Binary Search Tree Storage Rules 498
The Binary Search Tree Bag—Implementation of Some Simple Methods 503
Counting the Occurrences of an Element in a Binary Search Tree 504
Adding a New Element to a Binary Search Tree 505
Removing an Element from a Binary Search Tree 506
The addAll, addMany, and union Methods 510
Pitfall: Violating the addTree Precondition 511
Implementing addAll 512
Time Analysis and an Internal Iterator 513
Self-Test Exercises for Section 9.5 513
Chapter Summary 514
Solutions to Self-Test Exercises 514
Programming Projects 517
Contents xxiii

CHAPTER 10 TREE PROJECTS 520


10.1 Heaps 521
The Heap Storage Rules 521
The Priority Queue Class with Heaps 522
Adding an Element to a Heap 523
Removing an Element from a Heap 524
Self-Test Exercises for Section 10.1 527
10.2 B-Trees 527
The Problem of Unbalanced Trees 527
The B-Tree Rules 528
An Example B-Tree 529
The Set Class with B-Trees 530
Searching for an Element in a B-Tree 535
Programming Tip: Private Methods to Simplify Implementations 537
Adding an Element to a B-Tree 537
The Loose Addition Operation for a B-Tree 538
A Private Method to Fix an Excess in a Child 540
Back to the add Method 541
Employing Top-Down Design 543
Removing an Element from a B-Tree 543
The Loose Removal from a B-Tree 544
A Private Method to Fix a Shortage in a Child 546
Removing the Biggest Element from a B-Tree 549
Programming Tip: Write and Test Small Pieces 549
External B-Trees 550
Self-Test Exercises for Section 10.2 551
10.3 Java Support for Trees 552
The DefaultMutableTreeNode from javax.swing.tree 552
Using the JTree Class to Display a Tree in an Applet 552
The JApplet Class 552
Programming Tip: Adding a Component to a JApplet 553
What the TreeExample Applet Displays 553
Self-Test Exercises for Section 10.3 553
10.4 Trees, Logs, and Time Analysis 558
Time Analysis for Binary Search Trees 559
Time Analysis for Heaps 559
Logarithms 562
Logarithmic Algorithms 563
Self-Test Exercises for Section 10.4 563
Chapter Summary 563
Solutions to Self-Test Exercises 564
Programming Projects 566
xxiv Contents

CHAPTER 11 SEARCHING 567


11.1 Serial Search and Binary Search 568
Serial Search 568
Serial Search—Analysis 568
Binary Search 571
Binary Search—Design 572
Pitfall: Common Indexing Errors in Binary Search Implementations 574
Binary Search—Analysis 574
Java’s Binary Search Methods 579
Self-Test Exercises for Section 11.1 581
11.2 Open-Address Hashing 581
Introduction to Hashing 581
Noninteger Keys and Java’s hashCode Method 583
Pitfall: Classes Often Need a New hashCode Method 584
The Table ADT—Specification 584
The Table ADT—Design 587
The Table ADT—Implementation 589
A Practical Illustration of Open-Address Hashing 594
Choosing a Hash Function to Reduce Collisions 596
Double Hashing to Reduce Clustering 596
Self-Test Exercises for Section 11.2 598
11.3 Using Java’s Hashtable Class 599
11.4 Chained Hashing 600
Self-Test Exercises for Section 11.4 601
11.5 Programming Project: A Table Class Implemented with Java’s Vector and LinkedList 603
A New Table Class 603
Data Structures for the New Table Class 603
Implementing the New Table Class 604
Self-Test Exercises for Section 11.6 605
11.6 Time Analysis of Hashing 605
The Load Factor of a Hash Table 607
Self-Test Exercises for Section 11.5 609
Chapter Summary 609
Solutions to Self-Test Exercises 610
Programming Projects 612

CHAPTER 12 SORTING 614


12.1 Quadratic Sorting Algorithms 615
Selectionsort—Specification 615
Selectionsort—Design 616
Selectionsort—Testing 619
Selectionsort—Analysis 620
Programming Tip: Rough Estimates Suffice for Big-O 622
Insertionsort 622
Insertionsort—Analysis 626
Self-Test Exercises for Section 12.1 629
Random documents with unrelated
content Scribd suggests to you:
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookluna.com

You might also like