100% found this document useful (8 votes)
16 views

(eBook PDF) Data Structures and Other Objects Using Java 4th Edition download

The document provides links to various eBooks on data structures and Java programming, including multiple editions of titles such as 'Data Structures and Other Objects Using Java' and 'Data Structures and Problem Solving Using Java.' It outlines a structured approach to teaching data types, object-oriented programming, recursion, and algorithm analysis, emphasizing the importance of understanding both the specification and implementation of data structures. Additionally, it discusses advanced projects and flexibility in course material ordering to accommodate different student backgrounds.

Uploaded by

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

(eBook PDF) Data Structures and Other Objects Using Java 4th Edition download

The document provides links to various eBooks on data structures and Java programming, including multiple editions of titles such as 'Data Structures and Other Objects Using Java' and 'Data Structures and Problem Solving Using Java.' It outlines a structured approach to teaching data types, object-oriented programming, recursion, and algorithm analysis, emphasizing the importance of understanding both the specification and implementation of data structures. Additionally, it discusses advanced projects and flexibility in course material ordering to accommodate different student backgrounds.

Uploaded by

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

(eBook PDF) Data Structures and Other Objects

Using Java 4th Edition pdf download

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

Download more ebook from https://ebooksecure.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebooksecure.com
to discover even more!

(eBook PDF) Data Structures and Problem Solving Using


Java 4th Edition

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

(eBook PDF) Data Structures and Abstractions with Java


4th Edition

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

(eBook PDF) Data Structures and Abstractions with Java


4th Global Edition

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

(eBook PDF) Starting Out with Java: From Control


Structures through Data Structures 4th 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/

(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-objects-7th-edition/

(eBook PDF) Starting Out with Java: From Control


Structures through Data Structures 3rd Edition

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

(eBook PDF) Introduction to JAVA Programming and Data


Structures Comprehensive Version 11

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

(eBook PDF) Java Foundations: Introduction to Program


Design and Data Structures 5th Edition

http://ebooksecure.com/product/ebook-pdf-java-foundations-
introduction-to-program-design-and-data-structures-5th-edition/
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
Another Random Scribd Document
with Unrelated Content
IV

A Siege and its Heroine

T HE population of the region, friends and foes, were now up in


alarm. Reports met us of the outrages of the Ruffians upon Free
State settlers the night previous.
Here is the story of one of the depredations, detailed to us at one of
our halts.
It was upon a stanch old German and his family, settled near the
junction of the North and South branches of the Pottawatomie. Old
Kepler, as he was nicknamed, had not taken any leading or even
active part in the "troubles" (as they were termed), but his strong
anti-slavery sentiments had cropped out and were known to the
enemy.
They now made directly for his cabin, evidently resolved, as the
opportunity might offer, to force him to declare himself for one side
or the other. No man, in fact, in those days of the Kansas conflict,—
partisan, bitter, bloody,—could long occupy anything like neutral
ground. If one undertook to "sit on the fence," he soon became a
target for both parties and was relentlessly dislodged.
It was not the nature of the old German to dissemble, when the trial
came. On the approach of the Ruffians he prepared for the worst, as
he expected no favor. He barricaded his cabin door and refused their
demand for admittance. They burned his wheat and hay stacks, and
all his outbuildings, and then called upon the besieged to surrender.
It was believed, probably rightly, by the assailants, that the old man
was possessed of considerable money, brought with him from the
old country. This lent incitement to their attack; while, if true, the
fact was undoubtedly an additional motive on his part for keeping
the invaders at a distance.
Brave old Kepler was quite advanced in years. He was about three
score and ten, but all the old valorous Teutonic blood in his veins
was aroused, and he prepared to resist the spoilers even to the
death, if need be. His wife, partner of his New World adventures and
toils, had succumbed not long before to the frontier hardships and
had passed on. He had one son, a chip of the old block, brave,
strong, and inured to the rough Western life, equally interested with
the father in carving out their fortunes in this new country, and in
the making of their Western prairie home.
And there was an only daughter, alike the support and solace of both
father and brother;—the light, indeed, of the household and of the
neighborhood.
I must interpolate a word here, in passing, descriptive of this
daughter,—the worthy heroine of the event, as we shall see. She
was a light-haired, blond-complexioned young girl, with all the
proverbial German fairness,—bright and handsome as a prairie
flower. And she had the German habit of taking a share in the work
in the open field. Often was she seen by the passers up and down
the creek, "chopping in corn" (as they call it in the West),—keeping
even step in the row with her robust brother; or now driving the
cattle while he held the plough; then changing work with him,
guiding the share while he drove the oxen.
Her household duties, however, were not neglected meanwhile.
Doubtless the brother, in return, here gave her a helping hand.
Nowhere else on the road (as the writer can testify from personal
experience) did the weary and hungry traveler find such bread as
when thrown upon the Keplers' hospitality,—bread of this young
girl's manufacture.
Besides all this,—and appropriately to be said in this connection,—
this fair maiden could handle a rifle on occasion, as we shall
presently see. Such ability was often a quite useful accomplishment
for the gentler sex on our wild Western border. It proved eminently
so in the case before us.
The yelling, hooting, and now drunken mob began at length to fire
upon the cabin at its vulnerable points. The heroic inmates returned
the shots through the holes between the logs in the loft, and not
without effect. One of the assailants was seriously wounded and
several others less so. The battle grew warm, the effusion of blood
thus far serving only to increase the wild fury of the besiegers.
The father and son stood with their guns at the openings, while the
young girl loaded the pieces for them as fast as they were emptied.
At length the baffled and maddened crowd changed their tactics.
They managed to pile wood, logs, and rubbish against the cabin,
hoping to fire the building. There was danger that the dastardly
effort would prove only too successful. The flames began to crackle.
All now seemed lost, when suddenly the brave daughter unbarred
the cabin door and sprang forth with a bucket of water in her hand
to dash out the newly kindled flames. This was done from the girl's
own impulse at the moment. Had they divined her intention, the
father and brother would not have allowed it. The feat, however,
strange to say, was as successful as it was heroic and perilous.
The surprised besiegers were not actually cowardly and base enough
to fire upon the unarmed, defenseless girl. However, one of them
sprang from his covert behind a tree to seize her. But the old
backwoodsman father, watching breathlessly the scene below from
his post in the loft,—his hand and eye steadied to perfect accuracy
by the imminent danger,—sent a rifle-bullet straight to the heart of
the venturesome wretch, and he fell forward dead at the maiden's
feet.
The girl regained the door and, with the aid of her brother, who
hastened to her assistance, rebarred it securely. All was now again
safe for the time being,—and permanently, as it proved. The
marauders, overawed by this episode and by the generally
unexpected course of affairs,—one of their number being actually
killed and several others more or less severely wounded,—hastily fell
back to a safe distance and finally beat a retreat from the
neighborhood.
V

The March Resumed

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

Seeking the Enemy

IT will be asked, perhaps, why we came to this particular place. In


this little town were encamped, at this particular time, Captain
John Brown and his daring and trusty band of men.
"Old Brown," as he was most often called, was a tower of strength in
time of need. He had become by that time a veritable terror to the
enemy. Tell a Border Ruffian: "John Brown is coming," and he would
shake in his shoes, or would run away had he strength enough left
for locomotion. Missouri mothers frightened their babies to sleep or
to quietude by the sound of his name.
If our information were correct, the foe we sought largely
outnumbered us. What more natural than that we should, under the
circumstances, desire the counsel of the stanch old man, and his
help, if needed.
He had not looked for an invasion from the direction at present
threatened, but was daily expecting one from another quarter. He
detailed two small companies, Captain Shore's and Captain Cline's,—
two-thirds of his own command,—to join our force; then bade us
seek the enemy, with the direction, if we found them too strong for
us, to send back word to him, whereupon he would come to our aid.
Meanwhile, he said, he would stay with the remainder of his men
and guard the town.
We set out in the morning, early and hopefully. Scouts with fleet
horses were dispatched in advance, and we rapidly followed after.
Rumors of all wild and exaggerated sorts met us as we went. First, it
was said, there were three hundred of the enemy, well armed and
mounted; then there were five hundred men, strongly intrenched to
receive our attack; later, there were a thousand, coming to meet us.
At last we began to be a little apprehensive, possibly a grain
frightened. In the uncertainty, a messenger was sent back to
Captain Brown to say that probably we should need his help.
But we resolutely pushed on, if with somewhat slackened speed.
Presently a scout returned bearing reliable tidings. The position and
strength of the invaders had been quite accurately ascertained. They
were about three hundred in number, quietly encamped, and as yet
unaware of our approach.
Our officers decided not to wait for Captain Brown to come up, but
to press forward to the attack and by celerity of movement gain
what advantage was possible.
One point was, nevertheless, taken into consideration. We were but
about sixty in number, all told. We were prepared and determined to
do some hard fighting if necessary; but, it was argued, if we could
take the enemy by surprise, victory would be more fully assured us,
and much needless spilling of blood might be avoided.
We therefore proceeded cautiously till we arrived within two miles of
the hostile force, where our advanced scouts had taken up position
and were actually looking down with spy-glasses into the enemy's
camp and watching their every movement. The foe seemed wholly
unconscious of any impending danger.
VII

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

A Scene for a Painter

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

Brown's Night Appointment

W E gathered together the spoils and took up our march on the


backward track toward home, discussing the exciting events of
the day and recounting to each other our individual experiences,
adventures, and "hairbreadth escapes." When we had thus
proceeded some three miles, it was nearing sundown, and we halted
for supper and to determine our course for the night.
Meanwhile we had learned an important fact from our prisoners,
namely: that we had not met all of our enemies. A part of them,
quite a large force, had gone north that morning, and might be at
that very moment ravaging our own homes which we had left behind
the evening before. Naturally, these unwelcome tidings cast a cloud
across our rejoicings. They might after all be turned to mourning!
Having nearly finished our meal, and while we were yet speculating
on the situation, Captain Brown hastily rose to his feet and called
upon all those, who were ready to go with him, to mount their
horses. Forty or more men instantly sprang into their saddles, and
others were about to do the same, when the old man cried, "Enough
—and too many." He thanked them for their readiness, and then
selected thirty of the number, tried and trusted men who had
followed him before, and without asking why or whither. In the
present instance also they ventured not a question.
Brown seldom disclosed his intention or plans to any one. He wished
no man with him who was not absolutely reliable. He required the
implicit confidence of his followers and unquestioning obedience to
his commands. Whoever put himself under his leadership took his
life in his hand and followed whithersoever he was led.
On this occasion some not acquainted with his habits plied him with
queries as to where he was going and what he would do. He only
answered, characteristically, that he "had an appointment with some
Missourians and must not disappoint them." One ventured jocosely
to ask further, concerning the appointed place of meeting. He
replied, they had not been kind enough to fix upon the precise spot,
but he felt bound, out of courtesy, inasmuch as they came from a
distance, to hold himself in readiness when wanted. This left us, of
course, wholly in the dark as to his movements.
With some words of advice to those of us remaining,—that we would
better seek our homes, be prepared to defend them, and ready for
any action when needed,—he gave the command, "Ready! Forward!"
and, with a wave of his hand, led his Knights Errant away.
After they had departed it was decided that it would be advisible for
us to return to the camping-ground of the enemy and pitch our tents
there for the night; because, it was argued, when the detached force
gone north returned, they would naturally seek their friends in the
camp where they left them.
Accordingly, though weary near to exhaustion, we returned and
camped there, threw out our pickets, and made every preparation to
give the marauders a warm reception should they appear. We slept
on our arms, ready for any emergency, but the night passed and we
were undisturbed.
The next morning dawned on us clear and beautiful. All our
apprehensions of danger had passed with the darkness. Our pickets
were withdrawn. The scouts, who had been sent out to gather news
of the scattered settlers, had come back with no tidings of the foe
we had awaited. Consequently, relieved of all military restraint, we
gave ourselves up for the time to the preparation and enjoyment of
an early breakfast.
The wagons were unpacked of their provisions. The horses were
picketed, or were turned loose for grazing. The prisoners, disarmed,
were allowed comparative freedom. Fires were lighted here and
there for cooking. And thus we were spread out over a large area,
forgetful of the enemy, without a thought of an attack, and bent only
on making ready to satisfy the cravings of hunger.
X

An Intrepid Charge

T HEN occurred the scene which gives us one of the glimpses of


John Brown for the sake of which these reminiscences have been
written.
Suddenly, over the hill or rising ground some half or third of a mile
away, two horsemen came up at full speed.
"Look! look!" was whispered in suppressed voices from one to
another of our party, and all eyes were upturned in that direction.
Observing us, the horsemen as suddenly turned on their heels, and
disappeared the way they came, leaving us stupefied with doubt and
wonder.
In a moment more, however, the heads of a whole troop rose in
sight, and the cry, "The Missourians! the Missourians!" rang through
our camp in startling accents.
We were in dismay, for we were entirely unprepared for attack and
there was no time to make ready. We were apparently caught just as
our enemy had been surprised by ourselves. Men sprang, some for
their arms, some for their horses. Whether to fight or to try to
escape was uppermost in their minds,—each could settle that
question only for himself. At any rate, every one felt that a daring
and determined foe, apparently numbering a hundred, which was
double our own number, could, in the condition in which we were,
utterly cut us to pieces and destroy us at a blow.
What grave emotions that thought aroused! It is difficult for one,
never thrown into any such situation, to realize or in any degree
even imagine the feelings that may surge through the bosom of men
thus placed. Accounts have been given of what panic-stricken
crowds or armies will sometimes do, but a description of what they
feel on such occasions of disaster was never yet fully penned or
painted by man.
Meanwhile, some of our number, who had been cool enough to
observe the fiercely advancing cavaliers, perceived that they were
friends, not foes. It was old Captain Brown himself and his trusty
band. With joy, this news rang through our ranks. All eyes were then
directed toward them, enchained and enchanted. It was a splendid
sight.
They at first, naturally, took us for enemies, not dreaming but that
we were miles away, where they left us the evening before. They
suspected us to be the force, encamped there, which they had been
riding all night to overtake,—the same force we had awaited.
They came swiftly up over the brow of the hill, in full view, with
Brown at their head, and, without halting or even slackening their
speed, swung into line of battle. Only thirty men! yet they presented
a truly formidable array. The line was formed two deep, and was
stretched out to give the men full room for action. Brown sprang his
horse in front of the ranks, waving his long broadsword, and on they
came, sweeping down upon us with irresistible fury.
It was indeed a splendid and fearful sight, never to be forgotten by
the beholders. Only thirty men! yet they seemed a host. In their
every action, in their entire movements, seemed emblazoned, as in
their determined souls it was written, "Victory or death!"
Their leader looked the very impersonation of Battle. Many of us had
seen John Brown before, some of us a number of times, and under
trying circumstances. But now all felt that the real man we had
never before beheld. The daring, the intrepidity, the large resources
of the man, none of us had imagined till that moment.
Not a gun was discharged, their commander having given to his men
the same strict orders that were given at Bunker Hill of old, that they
should "reserve their fire till they could see the whites of their
enemy's eyes." But before they had quite gained that very
dangerous proximity to us, we succeeded in making them
understand that we were their friends.
Then such a glad shout as rent the air from both sides was seldom
ever heard, we believe, on any field even of victory. They were as
glad to find that we were their friends, as we, in our helpless
condition, were glad to learn that they were not our enemies.
The full intrepidity of Brown and his men, though it appeared to us
astounding, was not fully appreciable till we came to look at it
somewhat from their own view-point.
We were actually about eighty men, prisoners and all. But, spread
out as we were, with the many horses grazing, the scattered and
unpacked wagons, numerous camp-fires,—widely separated for
convenience,—arms stacked in some places, and men gathered in
groups in others, we presented altogether a formidable appearance.
What was more, this was enhanced by our peculiar position, so that,
to them, our numbers and strength were exaggerated, while our
weakness and confusion were concealed. Brown admitted to us
himself, afterward, that he thought he was undertaking to whip a
force of two or three hundred, while his men declared that they
believed they were actually charging upon not less than a thousand.
Brown's quick military eye took in, at the first, the supposed
situation; and, as in a flash, he decided what to do. All depended, he
concluded, upon rapidity of action. His only hope lay in striking a
sudden and crushing blow, for which we were unprepared, and from
which we could not recover till he had made victory sure. From the
time Brown's forces came in sight over the hill, till they were within
gunshot of us, hardly thirty seconds elapsed,—a very short notice in
which to prepare for action, even if an attack were expected.
XI

Brown to Our Prisoners

A FTER mutual congratulations over the bloodless and happy


conclusion of the adventure, we set our friends down with us to
eat the interrupted breakfast, to which they were prepared to do
ample justice. They had ridden all night, some forty or fifty miles, in
pursuit of the enemy,—had ridden all night, without rest or food,
from the time they left us, at dusk of evening, till they surprised us
that morning with their dauntless charge.
Another incident in connection with the events described it seems
fitting to mention, as affording a very interesting side-glance at the
character of our hero. After the meal, Captain Brown was asked by
our officers to give a talk to the prisoners taken the day before, who
were now drawn up in line for parole. He responded without an
instant's hesitation or a moment to think what he should say.
He spoke to them in a plain, simple, unpretentious way, but with a
directness, a force, and an eloquence withal, which doubtless
wonderfully impressed those addressed, as certainly it held spell-
bound all others who listened. Such vivid and indelible impression did
this speech of Brown make on the mind of the present writer that,
even after the lapse of these many years, he is able to reproduce it,
not only in substance, but almost word for word; and he has no
doubt of its exceptional character. Perhaps it was second only to that
immortal address which the hero made three years later to the court
at his trial in Virginia, which Emerson pronounced one of the three
most remarkable addresses in the world.
On the latter occasion, however, instead of a few plain, simple, rough
and ready, but intensely admiring followers, he had almost the whole
civilized world eagerly to hear and sacredly to preserve his utterance.
Brown's speech to the prisoners was probably not over five minutes
long in its delivery, but it lasted those forty trembling men a lifetime.
It was not known that one of them ever afterward ventured over the
Missouri border into the Kansas territory.
The address was as follows:
"Men of Missouri, one of your number has asked to see John Brown.
Here he is. Look at him, and hereafter remember that he is the
enemy of all evil-doers.
"And what of you yourselves, men! You are from a neighboring State.
What are you here for? You are invaders of this territory,—and for
evil purposes, you know as well as we know. You have been killing
our men, terrorizing our women and children, and destroying our
property,—houses, crops, and animals. So you stand here as
criminals.
"You are fighting for slavery. You want to make or keep other people
slaves. Do you not know that your wicked efforts will end in making
slaves of yourselves? You come here to make this a slave State. You
are fighting against liberty, which our Revolutionary fathers fought to
establish in this Republic, where all men should be free and equal,
with the inalienable rights of life, liberty, and the pursuit of
happiness. Therefore, you are traitors to liberty and to your country,
of the worst kind, and deserve to be hung to the nearest tree.
"But we shall not touch a hair of your heads. Have no fear. You are
deluded men. You have been deceived by men who are your elders
but not your betters. You have been misled into this wrong, by those
your leaders; thus, they are the real criminals and worse than
traitors, and, if we had them here instead of you, they would not find
such mercy at our hands.
"You we forgive. For, as you yourselves have confessed, we believe it
can be said of you that, as was said of them of old, you being
without knowledge, 'you know not what you do.' But hereafter you
will be without excuse.
"Go in peace. Go home and tell your neighbors and friends of your
mistake. We deprive you only of your arms, and do that only lest
some of you are not yet converted to the right. We let you go free of
punishment this time; but, do we catch you over the border again
committing depredations, you must not expect, nor will you receive,
any mercy.
"Go home, and become liberty-loving citizens of your State and
country, and your mistakes and misdeeds, as also the injuries which
you have inflicted upon us, will not have been in vain."
XII

Hard Lines

T HE personal experiences here related are of interest and have a


value mainly as they throw somewhat of fresh light upon the
character of the subject of this work, Captain Brown, and upon the
events and times in which he was the leading actor.
Those were troublous times,—times that indeed "tried the men's
souls" who experienced them. The hardships were severe. Danger
and disease, death by ruthless hands, and even death from
starvation, often stared us in the face. At one time we lived six
weeks solely on Indian-meal mixed with water and dried before the
fire, and that without even a condiment. This was our common fare
in times of scarcity. Bacon and molasses, and tea without milk or
sugar, were our luxuries in times of plenty.
For months, in the summer of '56, the men in our settlement never
had their clothes off, day or night, unless torn or worn off. On a trip
early in the summer mentioned, made by a companion and myself to
Kansas City for provisions, we chanced to come across John Brown
and his company encamped in the woods on a river-bank. After we
made ourselves known as friends we were invited into their camp. A
more ragged set of men than we found were rarely, we believe, ever
seen,—Brown worst off of all, for he would not fare better than his
men. They had no shirts to their backs, and their outer clothing was
worn or torn to tatters. While in camp, they were going barefoot to
save the remnants of their worn-out shoes for emergencies. And
withal, they were, they said, on short rations, having no bread, but
only Indian-meal and water. They were glad of the opportunity to
engage us to bring them provisions on our return, but they
confessed they were as short of money as they were of provisions,
which simply meant that we must share ours with them.
The men of our company worked hard by day to raise crops, with
their rifles near at hand, and slept in the "bush" at night to avoid
surprise and capture in their cabins. Only the women and children
ran the risk of remaining in the houses, in their defenselessness
trusting to the mercy of the enemy. That border life invited sickness,
especially the malaria of the low prairie. Our cabins were roughly
made, and so open that when it rained it was about as wet inside of
them as outside.
We had not time to dig wells, and in mid-summer the rivers were
low and the water so stagnant that we had to brush the green scum
from the surface when we dipped the water to drink or for other
uses. Every man, woman, and child of the settlement was ill with the
"fever and ague," so termed. There came near being an exception to
the rule. One man kept so full of whiskey, continuously, that the
ague didn't seem to have even a fighting chance; but at length the
liquor fell short, and the ague then found its opportunity and even
made up for lost time.
As for fire-arms with which to defend ourselves, we were not well
off. The famous Sharpe's rifles—"Beecher's Bibles," so-called, from
the great preacher's contribution of them—won Kansas to freedom
in large measure; but more by their terrible name than by virtue of
any large number of the weapons themselves. The Free State men
in Kansas actually had few of them.
When my older brother, with whom I went to the territory, and
myself called on Theodore Parker in Boston,—for one thing to ask
him if those going to Kansas would be helped to fire-arms,—he said

You might also like