(eBook PDF) Data Structures and Other Objects Using Java 4th Edition download
(eBook PDF) Data Structures and Other Objects Using Java 4th Edition download
https://ebooksecure.com/product/ebook-pdf-data-structures-and-
other-objects-using-java-4th-edition/
http://ebooksecure.com/product/ebook-pdf-data-structures-and-
problem-solving-using-java-4th-edition/
http://ebooksecure.com/product/ebook-pdf-data-structures-and-
abstractions-with-java-4th-edition/
http://ebooksecure.com/product/ebook-pdf-data-structures-and-
abstractions-with-java-4th-global-edition/
http://ebooksecure.com/product/ebook-pdf-starting-out-with-java-
from-control-structures-through-data-structures-4th-edition/
Data Structures and Abstractions with Java 5th Edition
(eBook PDF)
http://ebooksecure.com/product/data-structures-and-abstractions-
with-java-5th-edition-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-starting-out-with-java-
from-control-structures-through-objects-7th-edition/
http://ebooksecure.com/product/ebook-pdf-starting-out-with-java-
from-control-structures-through-data-structures-3rd-edition/
http://ebooksecure.com/product/ebook-pdf-introduction-to-java-
programming-and-data-structures-comprehensive-version-11/
http://ebooksecure.com/product/ebook-pdf-java-foundations-
introduction-to-program-design-and-data-structures-5th-edition/
Preface vii
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.
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.
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).
Chapter Dependencies
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)
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.
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.
Chapter List
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
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
IT did not require the narration of this stirring tale to nerve our
forward movement, but it certainly increased our determination to
proceed at all hazard.
Our next halt was made at the cabin, some miles further on, from
which, as mentioned in the first chapter, the young man whom we
all knew and counted as one of us had been borne off a prisoner. As
soon as it was made known, by the usual signs, that we were
friends, we were joyfully if tearfully greeted. The family, consisting of
aged parents, sister, brother's wife and little children, were in
despair. Dreadful anxiety filled their minds. It was an illustration of
the saying that "to know the worst is better than suspense." If in the
great cause then firing their hearts this family had seen that son and
brother shot down before their eyes, they would have borne the
affliction silently and with submission. But the terrible uncertainty as
to his fate wrought upon them. A price had previously been set upon
the young man's head, and they had reason to fear the worst for
him.
It must be added, in passing, that his beloved ones never saw him
again alive. The good fortune fell to us to liberate him the next day
from his captors, when we found him bound upon his horse, with his
hands lashed behind him and his feet tied together under the
animal; but, alas! his liberation gave him only a short respite from
death. He fell, only a few days after, heroically fighting at the battle
of Osawatomie.
Some miles beyond we had to make that ford of the Pottawatomie
river of unenviable fame, and which we looked upon as the danger-
point of all others in our journey; for there our enemy, we thought,
would most likely be in ambush. But we swam the swift, dark,
muddy stream, swelled by recent rains to a flood, with the water up
to our horses' backs, luckily without hindrance or serious mishap.
That ford was the notorious Dutch Henry's crossing, so-called,—
surely a gloomy, gruesome, and dreaded spot at that dark midnight
hour. There, close by, had been enacted, just two months prior, the
rightly named Pottawatomie tragedy, which made that locality, on
account of this bloody event, verily for the time the "storm center"
of the Kansas conflict. But, terrible as it was, it served a great
purpose and was speedily followed by good.
The hero of our sketch was the central figure in this tragic act of the
Kansas drama, as he was in most others at this trying period. Brown
was the cyclonic force, the lightning's flash in the darkness, that
cleared and lighted the way for the men of that day.
Despite all delays on the way, we made our forced night-march of
twenty-two or more miles in remarkably good time, and arrived at
our destination about two o'clock in the morning, as weary,
exhausted, and hungry a set of troopers as ever drew rein and
slipped stirrup to seek rest and refreshment.
The Adair Log Cabin.
It will be of interest to our readers to learn here that, a couple of
miles from the town,—our halting place,—we passed the log cabin of
the Adair family, which has such historic interest gathered about it,
and which we shall have occasion to mention again later.
It so happened, as we learned afterward, that the hero of our story
lodged under that roof that night. He was aroused from his slumbers
and watched us from the window as we marched past,—having been
reliably assured, by our advanced guard, that we were no
threatening foe, but his firmest and safest friends.
A photographic view of the cabin's exterior is given on the opposite
page, as it appears to-day; and nearly the same as it existed at that
early date, now almost fifty years ago.
The town referred to was Osawatomie, soon to be made famous by
the man who is the principal subject of these sketches.
We were challenged by friendly pickets on guard, who escorted us to
the old "block-house" reared for town defense, where we were glad
to find shelter, and especially to find food, for hungry we were
indeed.
To what a sumptuous feast were we welcomed on that occasion!
And yet, strange to relate, the recollection of it is not calculated to
make one's mouth water. It so happened that a side of bacon and a
barrel of hardtack were stored there, for just such emergencies as
the present one, and these were now pressed into our service.
Their edible condition was such as naturally to suggest certain
Scripture phrases as descriptive thereof;—of the bacon, "ancient of
days"; and of the biscuit, "fullness of life." As we crunched the latter
between our teeth, the peculiar, fresh, sweet-and-bitter taste,
commingling at every mouthful, told us too well of the "life"
ensconced therein. No comments were made, however, except the
ejaculation occasionally, by one and another, "Wormy!" " Wormy!"
However, nothing daunted, we paused not in our eating till our
ravenous hunger was appeased. And then, on the bare floor of
boards, rived roughly out of forest trees,—though it was a little
difficult to fit our forms to their ridges and hollows,—we gained a
few hours of as sweet and refreshing slumber as ever visited mortal
eyes.
VI
The Battle
I N less time than it takes to relate it, the plan of battle was
arranged.
Our men were divided into three companies. Two divisions were to
make flank movements, one on the right and the other on the left of
the foe, while the third was to assault directly in front. The plan of
attack was well conceived and as successfully executed.
We had a circuit of some miles to make to gain the flank positions. It
was quickly and silently traveled. In our division, detailed on the left
flank, hardly a word was spoken during a two hours' march. Each
man was busy with his own thoughts. It is said that persons in
critical situations will sometimes have their whole lives pass before
them. I believe that most of us, during this march, recalled nearly all
we had ever done or seen, known or felt.
We were suddenly awakened, at length, from such reveries, by the
crack of rifles and the clash of musketry, and by bullets actually
whizzing about our ears. So closely had we stolen the march on
them that when we opened fire we were actually more in danger
from the guns of our friends than from those of our foes.
The enemy were taken completely by surprise. As prisoners whom
we took told us afterward, they thought that "Old Brown" was surely
upon them; and their next and only thought was of escape. They left
all, and ran for dear life, some on foot, shoeless and hatless; others
springing to their horses, and, even without bridle or saddle,
desperately making the trial of flight. Perfectly bewildered, they ran
this way and that; and naturally, as our forces were positioned,
many ran directly into our hands.
The one thing they did not do well was to fight, except in the case of
a few desperate ones and of the leaders, who called in vain upon
their men to rally. Then they gave up all for lost, and each looked
out for himself. Many discharged their pieces at the first onslaught,
but so much at random that not a man of our number was fatally
injured, though several were more or less severely wounded. We
took many prisoners, and captured some thirty horses, all the
enemy's wagons and luggage, and much ammunition and arms. The
victory was complete.
Not until all was over did Captain Brown and his reserve come up,
though they had ridden hard to lend us a helping hand. He warmly
congratulated us, however, upon our good success, saying that he
could not have done it better himself, and that he was just as glad
and proud of our victory as though he had won it.
VIII
T HERE were incidents not a few, connected with the day and with
the central figure of our sketch, which would add interest to our
pages. One there was which especially impressed itself upon all
witnesses of it.
This relates to one of the enemy who was fatally wounded in the
battle. He desired very much, he said, to see "Old Brown" before he
died.
Captain Brown was informed of the wish, whereupon he rode up to
the wagon which served as ambulance, and, with somewhat of
sternness in his manner, said to the prisoner, "You wish to see me.
Here I am. Take a good look at me, and tell your friends, when you
get back to Missouri, what sort of man I am."
Then he added in a gentler tone, "We wish no harm to you or to
your companions. Stay at home, let us alone, and we shall be
friends. I wish you well."
The prisoner meanwhile had raised himself with great difficulty, and
viewed the old man from head to foot as if feasting his eyes on a
great curiosity. Then he sank back, pale and exhausted, as he
answered, "I don't see as you are so bad. You don't talk like it."
The countenance of Brown as he viewed the sufferer had changed
to a look of commiseration. The wounded man saw it, and, reaching
out his hand, said, "I thank you." Brown tenderly clasped it, and
replied, "God bless you," while he turned with tears in his eyes and
rode away.
The present writer was standing within a few feet of Brown at the
time, and naturally drank in the scene with a boy's eager curiosity
and susceptibility to impression.
It was a scene for a painter, and the artist could with
appropriateness have called his work, "The Conqueror Conquered."
But it was perfectly illustrative of the man and of the hero. Brown
was as brave as a lion. He seemed absolutely not to know fear. Yet
withal he possessed a heart tender as a child's or as the tenderest
woman's.
IX
An Intrepid Charge
Hard Lines