100% found this document useful (4 votes)
27 views

Download ebooks file Java Structures Data Structures in Java for the Principled Programmer 2nd edition Duane Bailey all chapters

Data

Uploaded by

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

Download ebooks file Java Structures Data Structures in Java for the Principled Programmer 2nd edition Duane Bailey all chapters

Data

Uploaded by

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

Visit https://ebookgate.

com to download the full version and


explore more ebooks

Java Structures Data Structures in Java for the


Principled Programmer 2nd edition Duane Bailey

_____ Click the link below to download _____


https://ebookgate.com/product/java-structures-data-
structures-in-java-for-the-principled-programmer-2nd-
edition-duane-bailey/

Explore and download more ebooks at ebookgate.com


Here are some recommended products that might interest you.
You can download now and explore!

Data structures and abstractions with Java 2nd ed Edition


Carrano

https://ebookgate.com/product/data-structures-and-abstractions-with-
java-2nd-ed-edition-carrano/

ebookgate.com

Java Software Structures Designing and Using Data


Structures 3rd Edition John Lewis

https://ebookgate.com/product/java-software-structures-designing-and-
using-data-structures-3rd-edition-john-lewis/

ebookgate.com

Data Structures Outside In with Java 1st Edition Sesh


Venugopal

https://ebookgate.com/product/data-structures-outside-in-with-
java-1st-edition-sesh-venugopal/

ebookgate.com

Data Structures Other Objects using Java 4th Edition


Michael Mann

https://ebookgate.com/product/data-structures-other-objects-using-
java-4th-edition-michael-mann/

ebookgate.com
Java Foundations Introduction to Program Design and Data
Structures 2nd Edition John Lewis

https://ebookgate.com/product/java-foundations-introduction-to-
program-design-and-data-structures-2nd-edition-john-lewis/

ebookgate.com

Data structures and algorithms made easy in Java data


structure and algorithmic puzzles 2nd Edition Narasimha
Karumanchi
https://ebookgate.com/product/data-structures-and-algorithms-made-
easy-in-java-data-structure-and-algorithmic-puzzles-2nd-edition-
narasimha-karumanchi/
ebookgate.com

Data Structures Problem Solving Using Java 4th Edition


Mark Allen Weiss

https://ebookgate.com/product/data-structures-problem-solving-using-
java-4th-edition-mark-allen-weiss/

ebookgate.com

Advanced Topics in Java Core Concepts in Data Structures


1st Edition Noel Kalicharan (Auth.)

https://ebookgate.com/product/advanced-topics-in-java-core-concepts-
in-data-structures-1st-edition-noel-kalicharan-auth/

ebookgate.com

Schaum s Outline sof Data Structures with Java Second


Edition John Hubbard

https://ebookgate.com/product/schaum-s-outline-sof-data-structures-
with-java-second-edition-john-hubbard/

ebookgate.com
Java Structures

Data Structures in Java for the Principled Programmer


The 7 Edition
(Software release 33)

Duane A. Bailey

Williams College
September 2007

This 7 text copyrighted 2005-2007 by

All rights are reserved by The Author.


No part of this draft publiciation may be reproduced or distributed in any form
without prior, written consent of the author.
Contents

Preface to First Edition xi

Preface to the Second Edition xiii

Preface to the “Root 7” Edition xv

0 Introduction 1
0.1 Read Me . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
0.2 He Can’t Say That, Can He? . . . . . . . . . . . . . . . . . . . . . 2

1 The Object-Oriented Method 5


1.1 Data Abstraction and Encapsulation . . . . . . . . . . . . . . . . . 6
1.2 The Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Object-Oriented Terminology . . . . . . . . . . . . . . . . . . . . 8
1.4 A Special-Purpose Class: A Bank Account . . . . . . . . . . . . . . 11
1.5 A General-Purpose Class: An Association . . . . . . . . . . . . . . 14
1.6 Sketching an Example: A Word List . . . . . . . . . . . . . . . . . 18
1.7 Sketching an Example: A Rectangle Class . . . . . . . . . . . . . 20
1.8 Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.9 Who Is the User? . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.10 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.11 Laboratory: The Day of the Week Calculator . . . . . . . . . . . . 29

2 Comments, Conditions, and Assertions 33


2.1 Pre- and Postconditions . . . . . . . . . . . . . . . . . . . . . . . 34
2.2 Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.3 Craftsmanship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.4 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.5 Laboratory: Using Javadoc Commenting . . . . . . . . . . . . . . 39

3 Vectors 43
3.1 The Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.2 Example: The Word List Revisited . . . . . . . . . . . . . . . . . . 47
3.3 Example: Word Frequency . . . . . . . . . . . . . . . . . . . . . . 48
3.4 The Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.5 Extensibility: A Feature . . . . . . . . . . . . . . . . . . . . . . . . 53
3.6 Example: L-Systems . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.7 Example: Vector-Based Sets . . . . . . . . . . . . . . . . . . . . . 57
3.8 Example: The Matrix Class . . . . . . . . . . . . . . . . . . . . . . 60
3.9 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
iv Contents

3.10 Laboratory: The Silver Dollar Game . . . . . . . . . . . . . . . . . 67

4 Generics 69
4.1 Motivation (in case we need some) . . . . . . . . . . . . . . . . . 70
4.1.1 Possible Solution: Specialization . . . . . . . . . . . . . . 71
4.2 Implementing Generic Container Classes . . . . . . . . . . . . . . 72
4.2.1 Generic Associations . . . . . . . . . . . . . . . . . . . . 72
4.2.2 Parameterizing the Vector Class . . . . . . . . . . . . . . 74
4.2.3 Restricting Parameters . . . . . . . . . . . . . . . . . . . . 79
4.3 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

5 Design Fundamentals 81
5.1 Asymptotic Analysis Tools . . . . . . . . . . . . . . . . . . . . . . 81
5.1.1 Time and Space Complexity . . . . . . . . . . . . . . . . . 82
5.1.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
5.1.3 The Trading of Time and Space . . . . . . . . . . . . . . . 91
5.1.4 Back-of-the-Envelope Estimations . . . . . . . . . . . . . . 92
5.2 Self-Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
5.2.1 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
5.2.2 Mathematical Induction . . . . . . . . . . . . . . . . . . . 101
5.3 Properties of Design . . . . . . . . . . . . . . . . . . . . . . . . . 108
5.3.1 Symmetry . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
5.3.2 Friction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
5.4 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
5.5 Laboratory: How Fast Is Java? . . . . . . . . . . . . . . . . . . . . 115

6 Sorting 119
6.1 Approaching the Problem . . . . . . . . . . . . . . . . . . . . . . 119
6.2 Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
6.3 Insertion Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
6.4 Mergesort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
6.5 Quicksort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
6.6 Radix Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
6.7 Sorting Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
6.8 Ordering Objects Using Comparators . . . . . . . . . . . . . . . . 140
6.9 Vector-Based Sorting . . . . . . . . . . . . . . . . . . . . . . . . . 143
6.10 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
6.11 Laboratory: Sorting with Comparators . . . . . . . . . . . . . . . 147

7 A Design Method 149


7.1 The Interface-Based Approach . . . . . . . . . . . . . . . . . . . . 149
7.1.1 Design of the Interface . . . . . . . . . . . . . . . . . . . . 150
7.1.2 Development of an Abstract Implementation . . . . . . . . 151
7.1.3 Implementation . . . . . . . . . . . . . . . . . . . . . . . . 152
7.2 Example: Development of Generators . . . . . . . . . . . . . . . . 152
7.3 Example: Playing Cards . . . . . . . . . . . . . . . . . . . . . . . 155
Contents v

7.4 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

8 Iterators 161
8.1 Java’s Enumeration Interface . . . . . . . . . . . . . . . . . . . . 161
8.2 The Iterator Interface . . . . . . . . . . . . . . . . . . . . . . . . . 163
8.3 Example: Vector Iterators . . . . . . . . . . . . . . . . . . . . . . 165
8.4 Example: Rethinking Generators . . . . . . . . . . . . . . . . . . 167
8.5 Example: Filtering Iterators . . . . . . . . . . . . . . . . . . . . . 170
8.6 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
8.7 Laboratory: The Two-Towers Problem . . . . . . . . . . . . . . . 175

9 Lists 179
9.1 Example: A Unique Program . . . . . . . . . . . . . . . . . . . . . 182
9.2 Example: Free Lists . . . . . . . . . . . . . . . . . . . . . . . . . . 183
9.3 Partial Implementation: Abstract Lists . . . . . . . . . . . . . . . 186
9.4 Implementation: Singly Linked Lists . . . . . . . . . . . . . . . . 188
9.5 Implementation: Doubly Linked Lists . . . . . . . . . . . . . . . . 201
9.6 Implementation: Circularly Linked Lists . . . . . . . . . . . . . . 206
9.7 Implementation: Vectors . . . . . . . . . . . . . . . . . . . . . . . 209
9.8 List Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
9.9 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
9.10 Laboratory: Lists with Dummy Nodes . . . . . . . . . . . . . . . . 215

10 Linear Structures 219


10.1 Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
10.1.1 Example: Simulating Recursion . . . . . . . . . . . . . . . 222
10.1.2 Vector-Based Stacks . . . . . . . . . . . . . . . . . . . . . 225
10.1.3 List-Based Stacks . . . . . . . . . . . . . . . . . . . . . . . 227
10.1.4 Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . 228
10.2 Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
10.2.1 Example: Solving a Coin Puzzle . . . . . . . . . . . . . . . 231
10.2.2 List-Based Queues . . . . . . . . . . . . . . . . . . . . . . 234
10.2.3 Vector-Based Queues . . . . . . . . . . . . . . . . . . . . . 235
10.2.4 Array-Based Queues . . . . . . . . . . . . . . . . . . . . . 238
10.3 Example: Solving Mazes . . . . . . . . . . . . . . . . . . . . . . . 242
10.4 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
10.5 Laboratory: A Stack-Based Language . . . . . . . . . . . . . . . . 247
10.6 Laboratory: The Web Crawler . . . . . . . . . . . . . . . . . . . . 251

11 Ordered Structures 253


11.1 Comparable Objects Revisited . . . . . . . . . . . . . . . . . . . . 253
11.1.1 Example: Comparable Ratios . . . . . . . . . . . . . . . . 254
11.1.2 Example: Comparable Associations . . . . . . . . . . . . . 256
11.2 Keeping Structures Ordered . . . . . . . . . . . . . . . . . . . . . 258
11.2.1 The OrderedStructure Interface . . . . . . . . . . . . . . . 258
11.2.2 The Ordered Vector and Binary Search . . . . . . . . . . . 259
vi Contents

11.2.3 Example: Sorting Revisited . . . . . . . . . . . . . . . . . 264


11.2.4 A Comparator-based Approach . . . . . . . . . . . . . . . 265
11.2.5 The Ordered List . . . . . . . . . . . . . . . . . . . . . . . 267
11.2.6 Example: The Modified Parking Lot . . . . . . . . . . . . . 270
11.3 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
11.4 Laboratory: Computing the “Best Of” . . . . . . . . . . . . . . . . 275

12 Binary Trees 277


12.1 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
12.2 Example: Pedigree Charts . . . . . . . . . . . . . . . . . . . . . . 280
12.3 Example: Expression Trees . . . . . . . . . . . . . . . . . . . . . . 281
12.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
12.4.1 The BinaryTree Implementation . . . . . . . . . . . . . . . 284
12.5 Example: An Expert System . . . . . . . . . . . . . . . . . . . . . 287
12.6 Traversals of Binary Trees . . . . . . . . . . . . . . . . . . . . . . 290
12.6.1 Preorder Traversal . . . . . . . . . . . . . . . . . . . . . . 291
12.6.2 In-order Traversal . . . . . . . . . . . . . . . . . . . . . . 293
12.6.3 Postorder Traversal . . . . . . . . . . . . . . . . . . . . . . 295
12.6.4 Level-order Traversal . . . . . . . . . . . . . . . . . . . . . 296
12.6.5 Recursion in Iterators . . . . . . . . . . . . . . . . . . . . 297
12.7 Property-Based Methods . . . . . . . . . . . . . . . . . . . . . . . 299
12.8 Example: Huffman Compression . . . . . . . . . . . . . . . . . . 303
12.9 Example Implementation: Ahnentafel . . . . . . . . . . . . . . . . 307
12.10Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
12.11Laboratory: Playing Gardner’s Hex-a-Pawn . . . . . . . . . . . . . 313

13 Priority Queues 315


13.1 The Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
13.2 Example: Improving the Huffman Code . . . . . . . . . . . . . . 317
13.3 A Vector-Based Implementation . . . . . . . . . . . . . . . . . . . 318
13.4 A Heap Implementation . . . . . . . . . . . . . . . . . . . . . . . 319
13.4.1 Vector-Based Heaps . . . . . . . . . . . . . . . . . . . . . 320
13.4.2 Example: Heapsort . . . . . . . . . . . . . . . . . . . . . . 326
13.4.3 Skew Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . 329
13.5 Example: Circuit Simulation . . . . . . . . . . . . . . . . . . . . . 333
13.6 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
13.7 Laboratory: Simulating Business . . . . . . . . . . . . . . . . . . 341

14 Search Trees 343


14.1 Binary Search Trees . . . . . . . . . . . . . . . . . . . . . . . . . . 343
14.2 Example: Tree Sort . . . . . . . . . . . . . . . . . . . . . . . . . . 345
14.3 Example: Associative Structures . . . . . . . . . . . . . . . . . . . 345
14.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
14.5 Splay Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
14.6 Splay Tree Implementation . . . . . . . . . . . . . . . . . . . . . 357
14.7 An Alternative: Red-Black Trees . . . . . . . . . . . . . . . . . . . 361
Contents vii

14.8 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363


14.9 Laboratory: Improving the BinarySearchTree . . . . . . . . . . . . 367

15 Maps 369
15.1 Example Revisited: The Symbol Table . . . . . . . . . . . . . . . . 369
15.2 The Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
15.3 Simple Implementation: MapList . . . . . . . . . . . . . . . . . . 372
15.4 Constant Time Maps: Hash Tables . . . . . . . . . . . . . . . . . . 374
15.4.1 Open Addressing . . . . . . . . . . . . . . . . . . . . . . . 375
15.4.2 External Chaining . . . . . . . . . . . . . . . . . . . . . . 383
15.4.3 Generation of Hash Codes . . . . . . . . . . . . . . . . . . 385
15.4.4 Hash Codes for Collection Classes . . . . . . . . . . . . . . 391
15.4.5 Performance Analysis . . . . . . . . . . . . . . . . . . . . . 392
15.5 Ordered Maps and Tables . . . . . . . . . . . . . . . . . . . . . . 392
15.6 Example: Document Indexing . . . . . . . . . . . . . . . . . . . . 395
15.7 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
15.8 Laboratory: The Soundex Name Lookup System . . . . . . . . . . 401

16 Graphs 403
16.1 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
16.2 The Graph Interface . . . . . . . . . . . . . . . . . . . . . . . . . 404
16.3 Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
16.3.1 Abstract Classes Reemphasized . . . . . . . . . . . . . . . 408
16.3.2 Adjacency Matrices . . . . . . . . . . . . . . . . . . . . . . 410
16.3.3 Adjacency Lists . . . . . . . . . . . . . . . . . . . . . . . . 416
16.4 Examples: Common Graph Algorithms . . . . . . . . . . . . . . . 422
16.4.1 Reachability . . . . . . . . . . . . . . . . . . . . . . . . . . 422
16.4.2 Topological Sorting . . . . . . . . . . . . . . . . . . . . . . 424
16.4.3 Transitive Closure . . . . . . . . . . . . . . . . . . . . . . 427
16.4.4 All Pairs Minimum Distance . . . . . . . . . . . . . . . . . 428
16.4.5 Greedy Algorithms . . . . . . . . . . . . . . . . . . . . . . 429
16.5 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
16.6 Laboratory: Converting Between Units . . . . . . . . . . . . . . . 439

A Answers 441
A.1 Solutions to Self Check Problems . . . . . . . . . . . . . . . . . . 441
A.2 Solutions to Odd-Numbered Problems . . . . . . . . . . . . . . . 451

B Beginning with Java 489


B.1 A First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
B.2 Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
B.2.1 Primitive Types . . . . . . . . . . . . . . . . . . . . . . . . 491
B.2.2 Reference Types . . . . . . . . . . . . . . . . . . . . . . . 493
B.3 Important Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
B.3.1 The structure.ReadStream Class . . . . . . . . . . . . . . . 494
B.3.2 The java.util.Scanner Class . . . . . . . . . . . . . . . . . 495
viii Contents

B.3.3 The PrintStream Class . . . . . . . . . . . . . . . . . . . . 496


B.3.4 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
B.4 Control Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . 498
B.4.1 Conditional Statements . . . . . . . . . . . . . . . . . . . 498
B.4.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
B.5 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
B.6 Inheritance and Subtyping . . . . . . . . . . . . . . . . . . . . . . 502
B.6.1 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . 502
B.6.2 Subtyping . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
B.6.3 Interfaces and Abstract Classes . . . . . . . . . . . . . . . 504
B.7 Use of the Assert Command . . . . . . . . . . . . . . . . . . . . . 506
B.8 Use of the Keyword Protected . . . . . . . . . . . . . . . . . . . 507

C Collections 511
C.1 Collection Class Features . . . . . . . . . . . . . . . . . . . . . . . 511
C.2 Parallel Features . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
C.3 Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512

D Documentation 513
D.1 Structure Package Hierarchy . . . . . . . . . . . . . . . . . . . . . 513
D.2 Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515

Index 517
for Mary,
my wife and best friend

without
the model of my mentors,
the comments of my colleagues,
the support of my students,
the friendship of my family
this book would never be

thank you!
Preface to the First Edition
“I T ’ S A WONDERFUL TIME TO BE ALIVE .” At least that’s what I’ve found myself
saying over the past couple of decades. When I first started working with com-
puters, they were resources used by a privileged (or in my case, persistent) few.
They were physically large, and logically small. They were cast from iron. The
challenge was to make these behemoths solve complex problems quickly.
Today, computers are everywhere. They are in the office and at home. They
speak to us on telephones; they zap our food in the microwave. They make
starting cars in New England a possibility. Everyone’s using them. What has
aided their introduction into society is their diminished size and cost, and in-
creased capability. The challenge is to make these behemoths solve complex
problems quickly.
Thus, while the computer and its applications have changed over time, the
challenge remains the same: How can we get the best performance out of the
current technology? The design and analysis of data structures lay the funda-
mental groundwork for a scientific understanding of what computers can do
efficiently. The motivations for data structure design work accomplished three
decades ago in assembly language at the keypunch are just as familiar to us to-
day as we practice our craft in modern languages on computers on our laps. The
focus of this material is the identification and development of relatively abstract
principles for structuring data in ways that make programs efficient in terms of
their consumption of resources, as well as efficient in terms of “programmability.”
In the past, my students have encountered this material in Pascal, Modula-2,
and, most recently, C++. None of these languages has been ideal, but each has
been met with increasing expectation. This text uses The Java Programming
Language1 —“Java”—to structure data. Java is a new and exciting language
that has received considerable public attention. At the time of this writing, for
example, Java is one of the few tools that can effectively use the Internet as a
computing resource. That particular aspect of Java is not touched on greatly
in this text. Still, Internet-driven applications in Java will need supporting data
structures. This book attempts to provide a fresh and focused approach to the
design and implementation of classic structures in a manner that meshes well
with existing Java packages. It is hoped that learning this material in Java
will improve the way working programmers craft programs, and the way future
designers craft languages.
Pedagogical Implications. This text was developed specifically for use with
CS2 in a standard Computer Science curriculum. It is succinct in its approach,
and requires, perhaps, a little more effort to read. I hope, though, that this text

1 Java is a trademark of Sun Microsystems, Incorporated.


xii Preface to the First Edition

becomes not a brief encounter with object-oriented data structure design, but a
touchstone for one’s programming future.
The material presented in this text follows the syllabus I have used for sev-
eral years at Williams. As students come to this course with experience using
Java, the outline of the text may be followed directly. Where students are new
to Java, a couple of weeks early in the semester will be necessary with a good
N
companion text to introduce the student to new concepts, and an introductory
NW

NE

Java language text or reference manual is recommended. For students that need
W

a quick introduction to Java we provide a tutorial in Appendix B. While the text


SW

SE

was designed as a whole, some may wish to eliminate less important topics
and expand upon others. Students may wish to drop (or consider!) the sec-
tion on induction (Section 5.2.2). The more nontraditional topics—including,
for example, iteration and the notions of symmetry and friction—have been in-
cluded because I believe they arm programmers with important mechanisms for
implementing and analyzing problems. In many departments the subtleties of
more advanced structures—maps (Chapter 15) and graphs (Chapter 16)—may
be considered in an algorithms course. Chapter 6, a discussion of sorting, pro-
vides very important motivating examples and also begins an early investigation
of algorithms. The chapter may be dropped when better examples are at hand,
but students may find the refinements on implementing sorting interesting.
Associated with this text is a Java package of data structures that is freely
available over the Internet for noncommercial purposes. I encourage students,
educators, and budding software engineers to download it, tear it down, build it
List up, and generally enjoy it. In particular, students of this material are encouraged
to follow along with the code online as they read. Also included is extensive
documentation gleaned from the code by javadoc. All documentation—within
the book and on the Web—includes pre- and postconditions. The motivation for
this style of commenting is provided in Chapter 2. While it’s hard to be militant
about commenting, this style of documentation provides an obvious, structured
approach to minimally documenting one’s methods that students can appreciate
and users will welcome. These resources, as well as many others, are available
from McGraw-Hill at http://www.mhhe.com/javastructures.
Three icons appear throughout the text, as they do in the margin. The
top “compass” icon highlights the statement of a principle—a statement that
nim encourages abstract discussion. The middle icon marks the first appearance of
a particular class from the structure package. Students will find these files at
McGraw-Hill, or locally, if they’ve been downloaded. The bottom icon similarly
marks the appearance of example code.
Finally, I’d like to note an unfortunate movement away from studying the
implementation of data structures, in favor of studying applications. In the
extreme this is a disappointing and, perhaps, dangerous precedent. The design
of a data structure is like the solution to a riddle: the process of developing the
answer is as important as the answer itself. The text may, however, be used as a
reference for using the structure package in other applications by selectively
avoiding the discussions of implementation.
Preface to the Second Edition
Since the first edition of Java Structures support for writing programs in Java2
has grown considerably. At that time the Java Development Toolkit consisted
of 504 classes in 23 packages3 In Java 1.2 (also called Java 2) Sun rolled out
1520 classes in 59 packages. This book is ready for Java 1.4, where the number
of classes and packages continues to grow.
Most computer scientists are convinced of the utility of Java for program-
ming in a well structured and platform independent manner. While there are
still significant arguments about important aspects of the language (for exam-
ple, support for generic types), the academic community is embracing Java, for
example, as the subject of the Computer Science Advanced Placement Exami-
nation.
It might seem somewhat perplexing to think that many aspects of the origi-
nal Java environment have been retracted (or deprecated) or reconsidered. The
developers at Sun have one purpose in mind: to make Java the indispensable
language of the current generation. As a result, documenting their progress on
the development of data structures gives us valuable insight into the process of
designing useful data structures for general purpose programming. Those stu-
dents and faculty considering a move to this second edition of Java Structures
will see first-hand some of the decisions that have been made in the interven-
ing years. During that time, for example, the Collection-based classes were
introduced, and are generally considered an improvement. Another force—
one similar to calcification—has left a trail of backwards compatible features
that are sometimes difficult to understand. For example, the Iterator class
was introduced, but the Enumeration class was not deprecated. One subject of
the first edition—the notion of Comparable classes—has been introduced into
a number of important classes including String and Integer. This is a step
forward and a reconsideration of what we have learned about that material has
lead to important improvements in the text.
Since the main purpose of the text is to demonstrate the design and behavior
of traditional data structures, we have not generally tracked the progress of
Java where it blurs the view. For example, Java 2 introduces a List interface
(we applaud) but the Vector class has been extended to include methods that
are, essentially, motivated by linked lists (we wonder). As this text points out
frequently, the purpose of an interface is often to provide reduced functionality.
If the data structure does not naturally provide the functionality required by the
application, it is probably not an effective tool for solving the problem: search
elsewhere for an effective structure.

2 The Java Programming Language is a trademark of Sun Microsystems, Incorporated.


3 David Flanagan, et al., Java in a Nutshell, O’Reilly & Associates.
xiv Preface to the Second Edition

As of this writing, more than 100, 000 individuals have searched for and
downloaded the structure package. To facilitate using the comprehensive set
of classes with the Java 2 environment, we have provided a number of features
that support the use of the structure package in more concrete applications.
Please see Appendix C.
Also new to this edition are more than 200 new problems, several dozen
exercises, and over a dozen labs we regularly use at Williams.
Acknowledgments. Several students, instructors, and classes have helped to
shape this edition of Java Structures. Parth Doshi and Alex Glenday—diligent
Williams students—pointed out a large number of typos and stretches of logic.
Kim Bruce, Andrea Danyluk, Jay Sachs, and Jim Teresco have taught this course
at Williams over the past few years, and have provided useful feedback. I tip
my hat to Bill Lenhart, a good friend and advisor, who has helped improve this
text in subtle ways. To Sean Sandys I am indebted for showing me new ways to
teach new minds.
The various reviewers have made, collectively, hundreds of pages of com-
ments that have been incorporated (as much as possible) into this edition:
Eleanor Hare and David Jacobs (Clemson University), Ram Athavale (North
Carolina State University), Yannick Daoudi (McGill University), Walter Daugh-
erty (Texas A&M University), Subodh Kumar (Johns Hopkins University), Toshimi
Minoura (Oregon State University), Carolyn Schauble (Colorado State Univer-
sity), Val Tannen (University of Pennsylvania), Frank Tompa (University of Wa-
terloo), Richard Wiener (University of Colorado at Colorado Springs), Cynthia
Brown Zickos (University of Mississippi), and my good friend Robbie Moll (Uni-
versity of Massachusetts). Deborah Trytten (University of Oklahoma) has re-
viewed both editions! Still, until expert authoring systems are engineered, au-
thors will remain human. Any mistakes left behind or introduced are purely
those of the author.
The editors and staff at McGraw-Hill–Kelly Lowery, Melinda Dougharty, John
Wannemacher, and Joyce Berendes–have attempted the impossible: to keep me
within a deadline. David Hash, Phil Meek, and Jodi Banowetz are responsible
for the look and feel of things. I am especially indebted to Lucy Mullins, Judy
Gantenbein, and Patti Evers whose red pens have often shown me a better way.
Betsy Jones, publisher and advocate, has seen it all and yet kept the faith:
thanks.
Be aware, though: long after these pages are found to be useless folly, my
best work will be recognized in my children, Kate, Megan, and Ryan. None
of these projects, of course, would be possible without the support of my best
friend, my north star, and my partner, Mary.

Enjoy!

Duane A. Bailey
Williamstown, May 2002

Preface to the 7 Edition
In your hand is a special edition of Java Structures designed for use with two
semesters of Williams’ course on data structures, Computer Science 136. This
version is only marginally different than the preceding edition, but is positioned
to make use of Java 5 (the trademarked name for version 1.5 of the JDK).
Because Java 5 may not be available (yet) on the platform you use, most of the
code available in this book will run on older JDK’s. The one feature that would
not be available is Java’s new Scanner class from the java.util package; an
alternative is my ReadStream class, which is lightly documented in Section B.3.1
on page 494. It is a feature of the structure package soon to be removed.
In making this book available in this paperbound format, my hope is that
you find it a more inviting place to write notes: additions, subtractions, and
updates that you’re likely to have discussed in class. Sometimes you’ll identify
improvements, and I hope you’ll pass those along to me. In any case, you can
download the software (as hundreds of thousands have done in the past) and
modify it as you desire.
On occasion, I will release new sections you can incorporate into your text,
including a discussion of how the structure package can make use of generic
types.
I have spent a considerable amount of time designing the structure pack-
age. The first structures were available 8 years ago when Java was still in its
infancy. Many of the structures have since been incorporated (directly or indi-
rectly) into Sun’s own JDK. (Yes, we’ve sold a few books in California.) Still, I
feel the merit of my approach is a slimness that, in the end, you will not find
surprising.
Meanwhile, for those of you keeping track, the following table (adapted
from the 121 cubic inch, 3 pound 6 ounce, Fifth edition of David Flanagan’s
essential Java in a Nutshell) demonstrates the growth of Java’s support:

JDK Packages Classes Features


1.0 8 212 First public version
1.1 23 504 Inner classes
1.2 (Java 2) 59 1520 Collection classes
1.3 76 1842 A “maintenance” release.
1.4 135 2991 Improvments, including assert
1.5 (Java 5) 166 3562 Generics, autoboxing, and “varargs.”

Seeing this reminds me of the comment made by Niklaus Wirth, designer of


Pascal and the first two releases of Modula. After the design team briefed him
on the slew of new features to be incorporated into Modula 3, he parried: “But,
what features have you removed?” A timeless question.

xvi Preface to the 7 Edition

Acknowledgments. This book was primarily written for students of Williams


College. The process of publishing and reviewing a text tends to move the focus
off campus and toward the bottom line. The Route 7 edition4 —somewhere
between editions 2 and 3—is an initial attempt to bring that focus back to those
students who made it all possible.
For nearly a decade, students at many institutions have played an important
role in shaping these resources. In this edition, I’m especially indebted to Katie
Creel ’10 (Williams) and Brian Bargh ’07 (Messiah): thanks!
Many colleagues, including Steve Freund ’95 (Stanford, now at Williams),
Jim Teresco ’92 (Union, now at Mount Holyoke), and especially Gene Chase ’65
(M.I.T., now at Messiah) continue to nudge this text in a better direction. Brent
Heeringa ’99 (Morris, now at Williams) showers all around him with youthful
enthusiasm.
And a most special thanks to Bill Mueller for the shot heard around the
world—the game-winning run that showed all things were possible. Called by
Joe Castiglione ’68 (Colgate, now at Fenway):
“Three-and-one to Mueller. One out, nineth inning. 10-9 Yankees,
runner at first. Here’s the pitch...swing and a High Drive Deep to
Right...Back Goes Sheffield to the Bullpen...AND IT IS GONE!...AND
THE RED SOX HAVE WON IT!...ON A WALKOFF TWO RUN HOMER
BY BILL MUELLER OFF MARIANO RIVERA! CAN YOU BELIEVE IT?!”
Have I been a Red Sox fan all my life? Not yet.
Finally, nothing would be possible without my running mate, my Sox buddy,
and my best friend, Mary.

Cheers!

Duane A. Bailey ’82 (Amherst, now at Williams)


Williamstown, September 2007

4 Route 7 is a scenic byway through the Berkshires and Green Mountains that eddies a bit as it
passes through Williamstown and Middlebury.
Chapter 0
Introduction

Concepts: This is an important notice.


. Approaches to this material Please have it translated.
. Principles —The Phone Company

Y OUR MOTHER probably provided you with constructive toys, like blocks or
Tinkertoys1 or Lego bricks. These toys are educational: they teach us to think
spatially and to build increasingly complex structures. You develop modules
that can be stuck together and rules that guide the building process.
If you are reading this book, you probably enjoyed playing with construc-
tive toys. You consider writing programs an artistic process. You have grown
from playing with blocks to writing programs. The same guidelines for building
structures apply to writing programs, save one thing: there is, seemingly, no
limit to the complexity of the programs you can write. I lie.
Well, almost. When writing large programs, the data structures that main-
tain the data in your program govern the space and time consumed by your
running program. In addition, large programs take time to write. Using differ-
ent structures can actually have an impact on how long it takes to write your
program. Choosing the wrong structures can cause your program to run poorly
or be difficult or impossible to implement effectively.
Thus, part of the program-writing process is choosing between different
structures. Ideally you arrive at solutions by analyzing and comparing their
various merits. This book focuses on the creation and analysis of traditional
data structures in a modern programming environment, The Java Programming
Language, or Java for short.

0.1 Read Me
As might be expected, each chapter is dedicated to a specific topic. Many of the
topics are concerned with specific data structures. The structures we will inves-
tigate are abstracted from working implementations in Java that are available
to you if you have access to the Internet.2 Other topics concern the “tools of the

1 All trademarks are recognized.


2 For more information, see http://www.cs.williams.edu/JavaStructures.
2 Introduction

trade.” Some are mathematical and others are philosophical, but all consider
the process of programming well.
The topics we cover are not all-inclusive. Some useful structures have been
left out. Instead, we will opt to learn the principles of programming data struc-
tures, so that, down the road, you can design newer and better structures your-
self.
Perhaps the most important aspect of this book is the set of problems at the
end of each section. All are important for you to consider. For some problems
I have attempted to place a reasonable hint or answer in the back of the book.
Why should you do problems? Practice makes perfect. I could show you how to
Unicycles: the ride a unicycle, but if you never practiced, you would never learn. If you study
ultimate riding and understand these problems, you will find your design and analytical skills
structure. are improved. As for your mother, she’ll be proud of you.
Sometimes we will introduce problems in the middle of the running text—
these problems do not have answers (sometimes they are repeated as formal
problems in the back of the chapter, where they do have answers)—they should
be thought about carefully as you are reading along. You may find it useful to
have a pencil and paper handy to help you “think” about these problems on the
fly.
Exercise 0.1 Call3 your Mom and tell her you’re completing your first exercise. If
you don’t have a phone handy, drop her a postcard. Ask her to verify that she’s
proud of you.
This text is brief and to the point. Most of us are interested in experimenting.
We will save as much time as possible for solving problems, perusing code, and
practicing writing programs. As you read through each of the chapters, you
might find it useful to read through the source code online. As we first consider
the text of files online, the file name will appear in the margin, as you see here.
Structure The top icon refers to files in the structure package, while the bottom icon
refers to files supporting examples.
One more point—this book, like most projects, is an ongoing effort, and
the latest thoughts are unlikely to have made it to the printed page. If you
are in doubt, turn to the website for the latest comments. You will also find
online documentation for each of the structures, generated from the code using
Example javadoc. It is best to read the online version of the documentation for the
most up-to-date details, as well as the documentation of several structures not
formally presented within this text.

0.2 He Can’t Say That, Can He?


Sure! Throughout this book are little political comments. These remarks may
seem trivial at first blush. Skip them! If, however, you are interested in ways

3 Don’t e-mail her. Call her. Computers aren’t everything, and they’re a poor medium for a mother’s
pride.
0.2 He Can’t Say That, Can He? 3

to improve your skills as a programmer and a computer scientist, I invite you


to read on. Sometimes these comments are so important that they appear as
principles: N

NW

NE
W
Principle 1 The principled programmer understands a principle well enough to

E
SW

SE
form an opinion about it. S

Self Check Problems


Solutions to these problems begin on page 441.
0.1 Where are the answers for “self check” problems found?
0.2 What are features of large programs?
0.3 Should you read the entire text?
0.4 Are principles statements of truth?

Problems
Solutions to the odd-numbered problems begin on page 451.
0.1 All odd problems have answers. Where do you find answers to prob-
lems? (Hint: See page 451.)
0.2 You are an experienced programmer. What five serious pieces of advice
would you give a new programmer?
0.3 Surf to the website associated with this text and review the resources
available to you.
0.4 Which of the following structures are described in this text (see Append-
ix D): BinarySearchTree, BinaryTree, BitSet, Map, Hashtable, List?
0.5 Surf to http://www.javasoft.com and review the Java resources avail-
able from Sun, the developers of Java.
0.6 Review documentation for Sun’s java.util package. (See the Core
API Documentation at http://www.javasoft.com.) Which of the following
data structures are available in this package: BinarySearchTree, BinaryTree,
BitSet, Dictionary, Hashtable, List?
0.7 Check your local library or bookstore for Java reference texts.
0.8 If you haven’t done so already, learn how to use your local Java pro-
gramming environment by writing a Java application to write a line of text.
(Hint: Read Appendix B.)
0.9 Find the local documentation for the structure package. If none is to
be found, remember that the same documentation is available over the Internet
from http://www.cs.williams.edu/JavaStructures.
0.10 Find the examples electronically distributed with the structure pack-
age. Many of these examples are discussed later in this text.
Chapter 1

The Object-Oriented Method

Concepts: I will pick up the hook.


. Data structures You will see something new.
Two things. And I call them
. Abstract data types
Thing One and Thing Two.
. Objects
These Things will not bite you.
. Classes They want to have fun.
. Interfaces —Theodor Seuss Geisel

C OMPUTER SCIENCE DOES NOT SUFFER the great history of many other disci-
plines. While other subjects have well-founded paradigms and methods, com-
puter science still struggles with one important question: What is the best method
to write programs? To date, we have no best answer. The focus of language de-
signers is to develop programming languages that are simple to use but provide
the power to accurately and efficiently describe the details of large programs
and applications. The development of Java is one such effort.
Throughout this text we focus on developing data structures using object-
oriented programming. Using this paradigm the programmer spends time devel- OOP:
oping templates for structures called classes. The templates are then used to Object-oriented
construct instances or objects. A majority of the statements in object-oriented programming.
programs involve sending messages to objects to have them report or change
their state. Running a program involves, then, the construction and coordina-
tion of objects. In this way languages like Java are object-oriented.
In all but the smallest programming projects, abstraction is a useful tool
for writing working programs. In programming languages including Pascal,
Scheme, and C, the details of a program’s implementation are hidden away in
its procedures or functions. This approach involves procedural abstraction. In
object-oriented programming the details of the implementation of data struc-
tures are hidden away within its objects. This approach involves data abstrac-
tion. Many modern programming languages use object orientation to support
basic abstractions of data. We review the details of data abstraction and the
design of formal interfaces for objects in this chapter.
6 The Object-Oriented Method

1.1 Data Abstraction and Encapsulation


If you purchase a donut from Morningside Bakery in Pittsfield, Massachusetts,
you can identify it as a donut without knowing its ingredients. Donuts are
circular, breadlike, and sweet. The particular ingredients in a donut are of little
concern to you. Of course, Morningside is free to switch from one sweetener to
another, as long as the taste is preserved.1 The donut’s ingredients list and its
construction are details that probably do not interest you.
Likewise, it is often unimportant to know how data structures are imple-
mented in order to appreciate their use. For example, most of us are familiar
with the workings or semantics of strings or arrays, but, if pressed, we might
find it difficult to describe their mechanics: Do all consecutive locations in the
array appear close together in memory in your computer, or are they far apart?
The answer is: it is unimportant. As long as the array behaves like an array or
the string behaves like a string we are happy. The less one knows about how
arrays or strings are implemented, the less one becomes dependent on a partic-
Macintosh and ular implementation. Another way to think about this abstractly is that the data
UNIX store structure lives up to an implicit “contract”: a string is an ordered list of charac-
strings ters, or elements of an array may be accessed in any order. The implementor of
differently. the data structure is free to construct it in any reasonable way, as long as all the
terms of the contract are met. Since different implementors are in the habit of
making very different implementation decisions, anything that helps to hide the
implementation details—any means of using abstraction—serves to make the
world a better place to program.
When used correctly, object-oriented programming allows the programmer
to separate the details that are important to the user from the details that are
only important to the implementation. Later in this book we shall consider very
general behavior of data structures; for example, in Section 10.1 we will study
structures that allow the user only to remove the most recently added item.
Such behavior is inherent to our most abstract understanding of how the data
structure works. We can appreciate the unique behavior of this structure even
though we haven’t yet discussed how these structures might be implemented.
Those abstract details that are important to the user of the structure—including
abstract semantics of the methods—make up its contract or interface. The in-
terface describes the abstract behavior of the structure. Most of us would agree
that while strings and arrays are very similar structures, they behave differently:
you can shrink or expand a string, while you cannot directly do the same with
an array; you can print a string directly, while printing an array involves explic-
itly printing each of its elements. These distinctions suggest they have distinct
abstract behaviors; there are distinctions in the design of their interfaces.
The unimportant details hidden from the user are part of what makes up
the implementation. We might decide (see Figure 1.1) that a string is to be

1 Apple cider is often used to flavor donuts in New England, but that decision decidedly changes

the flavor of the donut for the better. Some of the best apple cider donuts can be found at Atkin’s
apple farm in Amherst, Massachusetts.
1.2 The Object Model 7

Counted string

Data L I C K E T Y S P L I T !
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 n

Count 13

Terminated string

E
Data L I C K E T Y S P L I T ! O
S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 n

Figure 1.1 Two methods of implementing a string. A counted string explicitly records
its length. The terminated string’s length is determined by an end-of-string mark.

constructed from a large array of characters with an attendant character count.


Alternatively, we might specify the length implicitly by terminating the string
with a special end-of-string mark that is not used for any other purpose. Both
of these approaches are perfectly satisfactory, but there are trade-offs. The first
implementation (called a counted string) has its length stored explicitly, while
the length of the second implementation (called a terminated string) is implied.
It takes longer to determine the length of a terminated string because we have to
search for the end-of-string mark. On the other hand, the size of a terminated
string is limited only by the amount of available memory, while the longest
counted string is determined by the range of integers that can be stored in its
length field (often this is only several hundred characters). If implementors can
hide these details, users do not have to be distracted from their own important
design work. As applications mature, a fixed interface to underlying objects
allows alternative implementations of the object to be considered.
Data abstraction in languages like Java allows a structure to take responsibil-
ity for its own state. The structure knows how to maintain its own state without
bothering the programmer. For example, if two strings have to be concatenated
into a single string structure, a request might have to be made for a new allot-
ment of memory. Thankfully, because strings know how to perform operations
on themselves, the user doesn’t have to worry about managing memory.

1.2 The Object Model


To facilitate the construction of well-designed objects, it is useful to have a de-
sign method in mind. As alluded to earlier, we will often visualize the data for
our program as being managed by its objects. Each object manages its own data
that determine its state. A point on a screen, for example, has two coordinates.
8 The Object-Oriented Method

A medical record maintains a name, a list of dependents, a medical history, and


a reference to an insurance company. A strand of genetic material has a se-
quence of base pairs. To maintain a consistent state we imagine the program
manipulates the data within its objects only through messages or method calls
to the objects. A string might receive a message “tell me your length,” while
a medical record might receive a “change insurance” message. The string mes-
sage simply accesses information, while the medical record method may involve
changing several pieces of information in this and other objects in a consistent
manner. If we directly modify the reference to the insurance company, we may
forget to modify similar references in each of the dependents. For large applica-
tions with complex data structures, it can be extremely difficult to remember to
coordinate all the operations that are necessary to move a single complex object
from one consistent state to another. We opt, instead, to have the designer of
the data structure provide us a method for carefully moving between states; this
method is activated in response to a high-level message sent to the object.
This text, then, focuses on two important topics: (1) how we implement and
evaluate objects with methods that are logically complex and (2) how we might
use the objects we create. These objects typically represent data structures, our
primary interest. Occasionally we will develop control structures—structures
whose purpose is to control the manipulation of other objects. Control struc-
tures are an important concept and are described in detail in Chapter 8.

1.3 Object-Oriented Terminology


In Java, data abstraction is accomplished through encapsulation of data in an
object—an instance of a class. Like a record in other languages, an object has
fields. Unlike records, objects also contain methods. Fields and methods of an
object may be declared public, which means that they are visible to entities
outside the class, or protected, in which case they may only be accessed by
code within methods of the class.2 A typical class declaration is demonstrated
by the following simple class that keeps track of the ratio of two integer values:

public class Ratio


{
protected int numerator; // numerator of ratio
Ratio protected int denominator; // denominator of ratio

public Ratio(int top, int bottom)


// pre: bottom != 0
// post: constructs a ratio equivalent to top::bottom
{
numerator = top;
denominator = bottom;
reduce();

2 This is not quite the truth. For a discussion of the facts, see Appendix B.8.
1.3 Object-Oriented Terminology 9

public int getNumerator()


// post: return the numerator of the fraction
{
return numerator;
}

public int getDenominator()


// post: return the denominator of the fraction
{
return denominator;
}

public double getValue()


// post: return the double equivalent of the ratio
{
return (double)numerator/(double)denominator;
}

public Ratio add(Ratio other)


// pre: other is nonnull
// post: return new fraction--the sum of this and other
{
return new Ratio(this.numerator*other.denominator+
this.denominator*other.numerator,
this.denominator*other.denominator);
}

protected void reduce()


// post: numerator and denominator are set so that
// the greatest common divisor of the numerator and denominator is 1
{
int divisor = gcd(numerator,denominator);
if (denominator < 0) divisor = -divisor;
numerator /= divisor;
denominator /= divisor;
}

protected static int gcd(int a, int b)


// post: computes the greatest integer value that divides a and b
{
if (a < 0) return gcd(-a,b);
if (a == 0) {
if (b == 0) return 1;
else return b;
}
if (b < a) return gcd(b,a);
return gcd(b%a,a);
}
10 The Object-Oriented Method

public String toString()


// post: returns a string that represents this fraction.
{
return getNumerator()+"/"+getDenominator();
}
}

First, a Ratio object maintains the numerator and denominator as protected


ints that are not directly modifiable by the user. The Ratio method is a con-
structor: a method whose name is the same as that of the class. (The formal
comments at the top of methods are pre- and postconditions; we discuss these
in detail in Chapter 2.) The constructor is called whenever a new Ratio object is
formed. Constructors initialize all the fields of the associated object, placing the
object into a predictable and consistent initial state. We declare the construc-
tors for a class public. To construct a new Ratio object, users will have to call
these methods. The value method returns a double that represents the ratio,
while the getNumerator and getDenominator methods fetch the current values
of the numerator and denominator of the fraction. The add method is useful for
adding one Ratio to another; the result is a newly constructed Ratio object.
Finally, the toString method generates the preferred printable representation
of the object; we have chosen to represent it in fractional form.
Two methods, reduce and gcd, are utility methods. The gcd method com-
putes the greatest common divisor of two values using Euclid’s method, one of
the oldest numerical algorithms used today. It is used by the reduce method to
reduce the numerator and denominator to lowest terms by removing any com-
mon factors. Both are declared protected because computing the reduction is
not a necessary (or obvious) operation to be performed on ratios of integers;
it’s part of the implementation. The gcd method is declared static because
the algorithm can be used at any time—its utility is independent of the number
of Ratio objects that exist in our program. The reduce method, on the other
hand, works only with a Ratio object.

Exercise 1.1 Nearly everything can be improved. Are there improvements that
might be made to the gcd method? Can you write the method iteratively? Is
iteration an improvement?

As with the Ratio class, data fields are usually declared protected. To ma-
nipulate protected fields the user must invoke public methods. The following
example demonstrates the manipulation of the Ratio class:

public static void main(String[] args)


{
Ratio r = new Ratio(1,1); // r == 1.0
r = new Ratio(1,2); // r == 0.5
r.add(new Ratio(1,3)); // sum computed, but r still 0.5
r = r.add(new Ratio(2,8)); // r == 0.75
System.out.println(r.getValue()); // 0.75 printed
1.4 A Special-Purpose Class: A Bank Account 11

System.out.println(r.toString()); // calls toString()


System.out.println(r); // calls toString()
}

To understand the merit of this technique of class design, we might draw an


analogy between a well-designed object and a lightbulb for your back porch.
The protected fields and methods of an object are analogous to the internal de-
sign of the bulb. The observable features, including the voltage and the size of
the socket, are provided without giving any details about the implementation
of the object. If light socket manufacturers depended on a particular imple-
mentation of lightbulbs—for example the socket only supported bright xenon
bulbs—it might ultimately restrict the variety of suppliers of lightbulbs in the
future. Likewise, manufacturers of lightbulbs should be able to have a cer-
tain freedom in their implementation: as long as they only draw current in an
agreed-upon way and as long as their bulb fits the socket, they should be free
to use whatever design they want. Today, most lamps take either incandescent
or fluorescent bulbs.
In the same way that fields are encapsulated by a class, classes may be encap-
sulated by a package. A package is a collection of related classes that implement
some set of structures with a common theme. The classes of this text, for ex-
ample, are members of the structure package. In the same way that there are
users of classes, there are users of packages, and much of the analogy holds. In
particular, classes may be declared public, in which case they may be used by
anyone who imports the package into their program. If a class is not public, it
is automatically considered protected. These protected classes may only be
constructed and used by other classes within the same package.

1.4 A Special-Purpose Class: A Bank Account


We now look at the detailed construction of a simplistic class: a BankAccount.
Many times, it is necessary to provide a tag associated with an instance of a
data structure. You might imagine that your bank balance is kept in a database
at your bank. When you get money for a trip through the Berkshires, you swipe
your card through an automated teller bringing up your account. Your account Automated
number, presumably, is unique to your account. Nothing about you or your teller: a robotic
banking history is actually stored in your account number. Instead, that num- palm reader.
ber is used to find the record linked to your account: the bank searches for a
structure associated with the number you provide. Thus a BankAccount is a sim-
ple, but important, data structure. It has an account (an identifier that never
changes) and a balance (that potentially does change). The public methods of
such a structure are as follows:

public class BankAccount


{
public BankAccount(String acc, double bal)
// pre: account is a string identifying the bank account BankAccount
12 The Object-Oriented Method

// balance is the starting balance


// post: constructs a bank account with desired balance

public boolean equals(Object other)


// pre: other is a valid bank account
// post: returns true if this bank account is the same as other

public String getAccount()


// post: returns the bank account number of this account

public double getBalance()


// post: returns the balance of this bank account

public void deposit(double amount)


// post: deposit money in the bank account

public void withdraw(double amount)


// pre: there are sufficient funds in the account
// post: withdraw money from the bank account
}

The substance of these methods has purposefully been removed because, again,
it is unimportant for us to know exactly how a BankAccount is implemented.
We have ways to construct and compare BankAccounts, as well as ways to read
the account number or balance, or update the balance.
Let’s look at the implementation of these methods, individually. To build a
new bank account, you must use the new operator to call the constructor with
two parameters. The account number provided never changes over the life of
the BankAccount—if it were necessary to change the value of the account num-
ber, a new BankAccount would have to be made, and the balance would have to
be transferred from one to the other. The constructor plays the important role
of performing the one-time initialization of the account number field. Here is
the code for a BankAccount constructor:

protected String account; // the account number


protected double balance; // the balance associated with account

public BankAccount(String acc, double bal)


// pre: account is a string identifying the bank account
// balance is the starting balance
// post: constructs a bank account with desired balance
{
account = acc;
balance = bal;
}

Two fields—account and balance—of the BankAccount object are responsible


for maintaining the object’s state. The account keeps track of the account num-
ber, while the balance field maintains the balance.
1.4 A Special-Purpose Class: A Bank Account 13

Since account numbers are unique to BankAccounts, to check to see if two


accounts are “the same,” we need only compare the account fields. Here’s the
code:

public boolean equals(Object other)


// pre: other is a valid bank account
// post: returns true if this bank account is the same as other
{
BankAccount that = (BankAccount)other;
// two accounts are the same if account numbers are the same
return this.account.equals(that.account);
}

Notice that the BankAccount equals method calls the equals method of the key,
a String. Both BankAccount and String are nonprimitive types, or examples
of Objects. Every object in Java has an equals method. If you don’t explicitly
provide one, the system will write one for you. Generally speaking, one should
assume that the automatically written or default equals method is of little use.
This notion of “equality” of objects is often based on the complexities of our
abstraction; its design must be considered carefully.
One can ask the BankAccount about various aspects of its state by calling its
getAccount or getBalance methods:
public String getAccount()
// post: returns the bank account number of this account
{
return account;
}

public double getBalance()


// post: returns the balance of this bank account
{
return balance;
}

These methods do little more than pass along the information found in the
account and balance fields, respectively. We call such methods accessors. In a
different implementation of the BankAccount, the balance would not have to be
explicitly stored—the value might be, for example, the difference between two
fields, deposits and drafts. Given the interface, it is not much of a concern to
the user which implementation is used.
We provide two more methods, deposit and withdraw, that explicitly mod-
ify the current balance. These are mutator methods:

public void deposit(double amount)


// post: deposit money in the bank account
{
balance = balance + amount;
}
14 The Object-Oriented Method

public void withdraw(double amount)


// pre: there are sufficient funds in the account
// post: withdraw money from the bank account
{
balance = balance - amount;
}

Because we would like to change the balance of the account, it is important to


have a method that allows us to modify it. On the other hand, we purposefully
don’t have a setAccount method because we do not want the account number
to be changed without a considerable amount of work (work that, by the way,
models reality).
Here is a simple application that determines whether it is better to deposit
$100 in an account that bears 5 percent interest for 10 years, or to deposit $100
in an account that bears 2 21 percent interest for 20 years. It makes use of the
BankAccount object just outlined:

public static void main(String[] args)


{
// Question: is it better to invest $100 over 10 years at 5%
// or to invest $100 over 20 years at 2.5% interest?
BankAccount jd = new BankAccount("Jain Dough",100.00);
BankAccount js = new BankAccount("Jon Smythe",100.00);

for (int years = 0; years < 10; years++)


{
jd.deposit(jd.getBalance() * 0.05);
}
for (int years = 0; years < 20; years++)
{
js.deposit(js.getBalance() * 0.025);
}
System.out.println("Jain invests $100 over 10 years at 5%.");
System.out.println("After 10 years " + jd.getAccount() +
" has $" + jd.getBalance());
System.out.println("Jon invests $100 over 20 years at 2.5%.");
System.out.println("After 20 years " + js.getAccount() +
" has $" + js.getBalance());
}

Exercise 1.2 Which method of investment would you pick?

1.5 A General-Purpose Class: An Association


At least Dr. The following small application implements a Pig Latin translator based on a
Seuss started dictionary of nine words. The code makes use of an array of Associations,
with 50 words! each of which establishes a relation between an English word and its Pig Latin
1.5 A General-Purpose Class: An Association 15

translation. For each string passed as the argument to the main method, the
dictionary is searched to determine the appropriate translation.

public class atinLay {


// a pig latin translator for nine words
public static void main(String args[])
{ atinlay
// build and fill out an array of nine translations
Association dict[] = new Association[9];
dict[0] = new Association("a","aay");
dict[1] = new Association("bad","adbay");
dict[2] = new Association("had","adhay");
dict[3] = new Association("dad","adday");
dict[4] = new Association("day","ayday");
dict[5] = new Association("hop","ophay");
dict[6] = new Association("on","onay");
dict[7] = new Association("pop","oppay");
dict[8] = new Association("sad","adsay");

for (int argn = 0; argn < args.length; argn++)


{ // for each argument
for (int dictn = 0; dictn < dict.length; dictn++)
{ // check each dictionary entry
if (dict[dictn].getKey().equals(args[argn]))
System.out.println(dict[dictn].getValue());
}
}
}
}

When this application is run with the arguments hop on pop, the results are

ophay
onay
oppay

While this application may seem rather trivial, it is easy to imagine a large-scale
application with similar needs.3
We now consider the design of the Association. Notice that while the type
of data maintained is different, the purpose of the Association is very similar
to that of the BankAccount class we discussed in Section 1.4. An Association
is a key-value pair such that the key cannot be modified. Here is the interface
for the Association class:

import java.util.Map;

3 Pig Latin has played an important role in undermining court-ordered restrictions placed on music Association
piracy. When Napster—the rebel music trading firm—put in checks to recognize copyrighted music
by title, traders used Pig Latin translators to foil the recognition software!
16 The Object-Oriented Method

public class Association implements Map.Entry


{
public Association(Object key, Object value)
// pre: key is non-null
// post: constructs a key-value pair

public Association(Object key)


// pre: key is non-null
// post: constructs a key-value pair; value is null

public boolean equals(Object other)


// pre: other is non-null Association
// post: returns true iff the keys are equal

public Object getValue()


// post: returns value from association

public Object getKey()


// post: returns key from association

public Object setValue(Object value)


// post: sets association's value to value
}

For the moment, we will ignore the references to Map and Map.entry; these will
be explained later, in Chapter 15. What distinguishes an Association from a
more specialized class, like BankAccount, is that the fields of an Association
are type Object. The use of the word Object in the definition of an Association
makes the definition very general: any value that is of type Object—any non-
primitive data type in Java—can be used for the key and value fields.
Unlike the BankAccount class, this class has two different constructors:
protected Object theKey; // the key of the key-value pair
protected Object theValue; // the value of the key-value pair

public Association(Object key, Object value)


// pre: key is non-null
// post: constructs a key-value pair
{
Assert.pre(key != null, "Key must not be null.");
theKey = key;
theValue = value;
}

public Association(Object key)


// pre: key is non-null
// post: constructs a key-value pair; value is null
{
this(key,null);
}
1.5 A General-Purpose Class: An Association 17

The first constructor—the constructor distinguished by having two parame-


ters—allows the user to construct a new Association by initializing both fields.
On occasion, however, we may wish to have an Association whose key field is
set, but whose value field is left referencing nothing. (An example might be a
medical record: initially the medical history is incomplete, perhaps waiting to
be forwarded from a previous physician.) For this purpose, we provide a sin-
gle parameter constructor that sets the value field to null. Note that we use
this(key,null) as the body. The one-parameter constructor calls this object’s
two-parameter constructor with null as the second parameter. We write the
constructors in this dependent manner so that if the underlying implementation
of the Association had to be changed, only the two-parameter method would
have to be updated. It also reduces the complexity of the code and saves your
fingerprints!
Now, given a particular Association, it is useful to be able to retrieve the
key or value. Since the implementation is hidden, no one outside the class is
able to see it. Users must depend on the accessor methods to observe the data.

public Object getValue()


// post: returns value from association
{
return theValue;
}

public Object getKey()


// post: returns key from association
{
return theKey;
}

When necessary, the method setValue can be used to change the value associ-
ated with the key. Thus, the setValue method simply takes its parameter and
assigns it to the value field:

public Object setValue(Object value)


// post: sets association's value to value
{
Object oldValue = theValue;
theValue = value;
return oldValue;
}

There are other methods that are made available to users of the Association
class, but we will not discuss the details of that code until later. Some of the
methods are required, some are useful, and some are just nice to have around.
While the code may look complicated, we take the time to implement it cor- N
NW

NE

rectly, so that we will not have to reimplement it in the future.


W

E
SW

SE

S
Principle 2 Free the future: reuse code.
18 The Object-Oriented Method

It is difficult to fight the temptation to design data structures from scratch. We


shall see, however, that many of the more complex structures would be very
difficult to construct if we could not base our implementations on the results of
previous work.

1.6 Sketching an Example: A Word List


Suppose we’re interested in building a game of Hangman. The computer selects
random words and we try to guess them. Over several games, the computer
should pick a variety of words and, as each word is used, it should be removed
from the word list. Using an object-oriented approach, we’ll determine the
essential features of a WordList, the Java object that maintains our list of words.
Our approach to designing the data structures has the following five informal
steps:

1. Identify the types of operations you expect to perform on your object.


What operations access your object only by reading its data? What opera-
tions might modify or mutate your objects?

2. Identify, given your operations, those data that support the state of your
object. Information about an object’s state is carried within the object
between operations that modify the state. Since there may be many ways
to encode the state of your object, your description of the state may be
very general.

3. Identify any rules of consistency. In the Ratio class, for example, it would
not be good to have a zero denominator. Also, the numerator and denom-
inator should be in lowest terms.

4. Determine the number and form of the constructors. Constructors are


synthetic: their sole responsibility is to get a new object into a good initial
and consistent state. Don’t forget to consider the best state for an object
constructed using the parameterless default constructor.

5. Identify the types and kinds of information that, though declared pro-
tected, can efficiently provide the information needed by the public
methods. Important choices about the internals of a data structure are
usually made at this time. Sometimes, competing approaches are devel-
oped until a comparative evaluation can be made. That is the subject of
much of this book.

The operations necessary to support a list of words can be sketched out


easily, even if we don’t know the intimate details of constructing the Hangman
game itself. Once we see how the data structure is used, we have a handle on
the design of the interface. Thinking about the overall design of Hangman, we
can identify the following general use of the WordList object:
1.6 Sketching an Example: A Word List 19

WordList list; // declaration


String targetWord;

list = new WordList(10); // construction WordList


list.add("disambiguate"); // is this a word? how about ambiguate?
list.add("inputted"); // really? what verbification!
list.add("subbookkeeper"); // now that's coollooking!
while (!list.isEmpty()) // game loop
{
targetWord = list.selectAny(); // selection
// ...play the game using target word...
list.remove(targetWord); // update
}

Let’s consider these lines. One of the first lines (labeled declaration) de-
clares a reference to a WordList. For a reference to refer to an object, the object
must be constructed. We require, therefore, a constructor for a WordList. The
construction line allocates an initially empty list of words ultimately contain-
ing as many as 10 words. We provide an upper limit on the number of words
that are potentially stored in the list. (We’ll see later that providing such infor-
mation can be useful in designing efficient data structures.) On the next three
lines, three (dubious) words are added to the list.
The while loop accomplishes the task of playing Hangman with the user.
This is possible as long as the list of words is not empty. We use the isEmpty
method to test this fact. At the beginning of each round of Hangman, a random
word is selected (selectAny), setting the targetWord reference. To make things
interesting, we presume that the selectAny method selects a random word each
time. Once the round is finished, we use the remove method to remove the word
from the word list, eliminating it as a choice in future rounds.
There are insights here. First, we have said very little about the Hangman
game other than its interaction with our rather abstract list of words. The details
of the screen’s appearance, for example, do not play much of a role in under-
standing how the WordList structure works. We knew that a list was necessary
for our program, and we considered the program from the point of view of the
object. Second, we don’t really know how the WordList is implemented. The
words may be stored in an array, or in a file on disk, or they may use some tech-
nology that we don’t currently understand. It is only important that we have
faith that the structure can be implemented. We have sketched out the method
headers, or signatures, of the WordList interface, and we have faith that an im-
plementation supporting the interface can be built. Finally we note that what
we have written is not a complete program. Still, from the viewpoint of the
WordList structure, there are few details of the interface that are in question.
A reasoned individual should be able to look at this design and say “this will
work—provided it is implemented correctly.” If a reviewer of the code were to
ask a question about how the structure works, it would lead to a refinement of
our understanding of the interface.
We have, then, the following required interface for the WordList class:
20 The Object-Oriented Method

public class WordList


{
public WordList(int size)
// pre: size >= 0
// post: construct a word list capable of holding "size" words

public boolean isEmpty()


// post: return true iff the word list contains no words

public void add(String s)


// post: add a word to the word list, if it is not already there

public String selectAny()


// pre: the word list is not empty
// post: return a random word from the list

public void remove(String word)


// pre: word is not null
// post: remove the word from the word list
}

We will leave the implementation details of this example until later. You might
consider various ways that the WordList might be implemented. As long as
the methods of the interface can be supported by your data structure, your
implementation is valid.

Exercise 1.3 Finish the sketch of the WordList class to include details about the
state variables.

1.7 Sketching an Example: A Rectangle Class


Suppose we are developing a graphics system that allows the programmer to
draw on a DrawingWindow. This window has, associated with it, a Cartesian
coordinate system that allows us to uniquely address each of the points within
the window. Suppose, also, that we have methods for drawing line segments,
say, using the Line object. How might we implement a rectangle—called a
Rect—to be drawn in the drawing window?
One obvious goal would be to draw a Rect on the DrawingWindow. This
might be accomplished by drawing four line segments. It would be useful to
be able to draw a filled rectangle, or to erase a rectangle (think: draw a filled
rectangle in the background color). We’re not sure how to do this efficiently, but
these latter methods seem plausible and consistent with the notion of drawing.
(We should check to see if it is possible to draw in the background color.) This
leads to the following methods:

Rect public void fillOn(DrawingTarget d)


// pre: d is a valid drawing window
// post: the rectangle is filled on the drawing window d
1.7 Sketching an Example: A Rectangle Class 21

public void clearOn(DrawingTarget d)


// pre: d is a valid drawing window
// post: the rectangle is erased from the drawing window

public void drawOn(DrawingTarget d)


// pre: d is a valid drawing window
// post: the rectangle is drawn on the drawing window

It might be useful to provide some methods to allow us to perform basic calcu-


lations—for example, we might want to find out if the mouse arrow is located
within the Rect. These require accessors for all the obvious data. In the hope
that we might use a Rect multiple times in multiple locations, we also provide
methods for moving and reshaping the Rect.
public boolean contains(Pt p)
// pre: p is a valid point
// post: true iff p is within the rectangle

public int left()


// post: returns left coordinate of the rectangle

public void left(int x)


// post: sets left to x; dimensions remain unchanged

public int width()


// post: returns the width of the rectangle

public void width(int w)


// post: sets width of rectangle, center and height unchanged

public void center(Pt p)


// post: sets center of rect to p; dimensions remain unchanged

public void move(int dx, int dy)


// post: moves rectangle to left by dx and down by dy

public void moveTo(int left, int top)


// post: moves left top of rectangle to (left,top);
// dimensions are unchanged

public void extend(int dx, int dy)


// post: moves sides of rectangle outward by dx and dy

Again, other approaches might be equally valid. No matter how we might rep-
resent a Rect, however, it seems that all rectangular regions with horizontal
and vertical sides can be specified with four integers. We can, then, construct a
Rect by specifying, say, the left and top coordinates and the width and height.
For consistency’s sake, it seems appropriate to allow rectangles to be drawn
anywhere (even off the screen), but the width and height should be non-negative
22 The Object-Oriented Method

values. We should make sure that these constraints appear in the documenta-
tion associated with the appropriate constructors and methods. (See Section 2.2
for more details on how to write these comments.)
Given our thinking, we have some obvious Rect constructors:

public Rect()
// post: constructs a trivial rectangle at origin

public Rect(Pt p1, Pt p2)


// post: constructs a rectangle between p1 and p2

public Rect(int x, int y, int w, int h)


// pre: w >= 0, h >= 0
// post: constructs a rectangle with upper left (x,y),
// width w, height h

We should feel pleased with the progress we have made. We have developed
the signatures for the rectangle interface, even though we have no immediate
application. We also have some emerging answers on approaches to implement-
ing the Rect internally. If we declare our Rect data protected, we can insulate
ourselves from changes suggested by inefficiencies we may yet discover.

Exercise 1.4 Given this sketch of the Rect interface, how would you declare the
private data associated with the Rect object? Given your approach, describe how
you might implement the center(int x, int y) method.

1.8 Interfaces
Sometimes it is useful to describe the interface for a number of different classes,
without committing to an implementation. For example, in later sections of this
text we will implement a number of data structures that are able to be modified
by adding or removing values. We can, for all of these classes, specify a few of
their fundamental methods by using the Java interface declaration:

public interface Structure


{
public int size();
Structure // post: computes number of elements contained in structure

public boolean isEmpty();


// post: return true iff the structure is empty

public void clear();


// post: the structure is empty

public boolean contains(Object value);


// pre: value is non-null
// post: returns true iff value.equals some value in structure
1.8 Interfaces 23

public void add(Object value);


// pre: value is non-null
// post: value has been added to the structure
// replacement policy is not specified

public Object remove(Object value);


// pre: value is non-null
// post: an object equal to value is removed and returned, if found

public java.util.Enumeration elements();


// post: returns an enumeration for traversing structure;
// all structure package implementations return
// an AbstractIterator

public Iterator iterator();


// post: returns an iterator for traversing structure;
// all structure package implementations return
// an AbstractIterator

public Collection values();


// post: returns a Collection that may be used with
// Java's Collection Framework
}

Notice that the body of each method has been replaced by a semicolon. It
is, in fact, illegal to specify any code in a Java interface. Specifying just the
method signatures in an interface is like writing boilerplate for a contract with-
out committing to any implementation. When we decide that we are interested
in constructing a new class, we can choose to have it implement the Structure
interface. For example, our WordList structure of Section 1.6 might have made
use of our Structure interface by beginning its declaration as follows:

public class WordList implements Structure

When the WordList class is compiled by the Java compiler, it checks to see that
each of the methods mentioned in the Structure interface—add, remove, size, WordList
and the others—is actually implemented. In this case, only isEmpty is part of
the WordList specification, so we must either (1) not have WordList implement
the Structure interface or (2) add the methods demanded by Structure.
Interfaces may be extended. Here, we have a possible definition of what it
means to be a Set:

public interface Set extends Structure


{
public void addAll(Structure other);
// pre: other is non-null Set
// post: values from other are added into this set
24 The Object-Oriented Method

public boolean containsAll(Structure other);


// pre: other is non-null
// post: returns true if every value in set is in other

public void removeAll(Structure other);


// pre: other is non-null
// post: values of this set contained in other are removed

public void retainAll(Structure other);


// pre: other is non-null
// post: values not appearing in the other structure are removed
}

A Set requires several set-manipulation methods—addAll (i.e., set union) retain-


All (set intersection), and removeAll (set difference)—as well as the meth-
ods demanded by being a Structure. If we implement these methods for the
WordList class and indicate that WordList implements Set, the WordList class
could be used wherever either a Structure or Set is required. Currently, our
WordList is close to, but not quite, a Structure. Applications that demand
the functionality of a Structure will not be satisfied with a WordList. Having
the class implement an interface increases the flexibility of its use. Still, it may
require considerable work for us to upgrade the WordList class to the level of
a Structure. It may even work against the design of the WordList to provide
the missing methods. The choices we make are part of an ongoing design pro-
cess that attempts to provide the best implementations of structures to meet the
demands of the user.

1.9 Who Is the User?


When implementing data structures using classes and interfaces, it is sometimes
hard to understand why we might be interested in hiding the implementation.
After all, perhaps we know that ultimately we will be the only programmers
making use of these structures. That might be a good point, except that if
you are really a successful programmer, you will implement the data structure
flawlessly this week, use it next week, and not return to look at the code for
a long time. When you do return, your view is effectively that of a user of the
code, with little or no memory of the implementation.
One side effect of this relationship is that we have all been reminded of the
need to write comments. If you do not write comments, you will not be able to
read the code. If, however, you design, document, and implement your interface
carefully, you might not ever have to look at the implementation! That’s good
news because, for most of us, in a couple of months our code is as foreign to
us as if someone else had implemented it. The end result: consider yourself a
user and design and abide by your interface wherever possible. If you know of
some public field that gives a hint of the implementation, do not make use of it.
Instead, access the data through appropriate methods. You will be happy you
1.10 Conclusions 25
N

NW

NE
did later, when you optimize your implementation.

E
SW

SE
S
Principle 3 Design and abide by interfaces as though you were the user.

A quick corollary to this statement is the following:

Principle 4 Declare data fields protected.


N

NW

NE
W

E
If the data are protected, you cannot access them from outside the class, and

SW

SE
S

you are forced to abide by the restricted access of the interface.

1.10 Conclusions
The construction of substantial applications involves the development of com-
plex and interacting structures. In object-oriented languages, we think of these
structures as objects that communicate through the passing of messages or,
more formally, the invocation of methods.
We use object orientation in Java to write the structures found in this book.
It is possible, of course, to design data structures without object orientation, but
any effective data structuring model ultimately depends on the use of some form
of abstraction that allows the programmer to avoid considering the complexities
of particular implementations.
In many languages, including Java, data abstraction is supported by sepa-
rating the interface from the implementation of the data structure. To ensure
that users cannot get past the interface to manipulate the structure in an uncon-
trolled fashion, the system controls access to fields, methods, and classes. The
implementor plays an important role in making sure that the structure is usable,
given the interface. This role is so important that we think of implementation
as supporting the interface—sometimes usefully considered a contract between
the implementor and the user. This analogy is useful because, as in the real
world, if contracts are violated, someone gets upset!
Initial design of the interfaces for data structures arises from considering
how they are used in simple applications. Those method calls that are required
by the application determine the interface for the new structure and constrain,
in various ways, the choices we make in implementing the object.
In our implementation of an Association, we can use the Object class—
that class inherited by all other Java classes—to write very general data struc-
tures. The actual type of value that is stored in the Association is determined
by the values passed to the constructors and mutators of the class. This abil-
ity to pass a subtype to any object that requires a super type is a strength of
object-oriented languages—and helps to reduce the complexity of code.
26 The Object-Oriented Method

Self Check Problems


Solutions to these problems begin on page 441.
1.1 What is meant by abstraction?
1.2 What is procedural abstraction?
1.3 What is data abstraction?
1.4 How does Java support the concept of a message?
1.5 What is the difference between an object and a class?
1.6 What makes up a method’s signature?
1.7 What is the difference between an interface and an implementation?
1.8 What is the difference between an accessor and a mutator?
1.9 A general purpose class, such as an Association, often makes use of
parameters of type Object. Why?
1.10 What is the difference between a reference and an object?
1.11 Who uses a class?

Problems
Solutions to the odd-numbered problems begin on page 451.
1.1 Which of the following are primitive Java types: int, Integer, double,
Double, String, char, Association, BankAccount, boolean, Boolean?
1.2 Which of the following variables are associated with valid constructor
calls?
BankAccount a,b,c,d,e,f;
Association g,h;
a = new BankAccount("Bob",300.0);
b = new BankAccount(300.0,"Bob");
c = new BankAccount(033414,300.0);
d = new BankAccount("Bob",300);
e = new BankAccount("Bob",new Double(300));
f = new BankAccount("Bob",(double)300);
g = new Association("Alice",300.0);
h = new Association("Alice",new Double(300));

1.3 For each pair of classes, indicate which class extends the other:
a. java.lang.Number, java.lang.Double
b. java.lang.Number, java.lang.Integer
c. java.lang.Number, java.lang.Object
d. java.util.Stack, java.util.Vector
Random documents with unrelated
content Scribd suggests to you:
“Forgive me for wearying you, Fräulein. I am afraid I am rather
an enthusiast on the subject of education. But I won’t bore you any
more with my theories.”
“You are trying to revenge yourself upon the Queen by torturing
her through her son!” burst from Fräulein von Staubach.
“Surely, Fräulein, you must be aware that her Majesty makes my
post such a delightful one, and responds with so much alacrity to the
slightest suggestion I may venture to make for her guidance, that
the feeling at which you hint would be entirely out of place and
uncalled for?”
“She—she has not perhaps treated you as graciously as you
may have expected; but then, is it noble—is it even manly—to act in
this way? To work upon an unhappy mother’s feelings——”
“Fräulein, permit me to remind you that you are speaking of her
Majesty in terms for which there is no justification. If I had any wish
for revenge—to which you seem to consider I am entitled—I could
find no better way of wreaking it than by simply resigning my office
and returning to England. I am actuated by no feelings but those of
the greatest respect and kindness towards the Queen, who was left
in my charge under the most solemn circumstances by my dead
friend. It is not my fault, but I fear it will be her own great
misfortune, that she herself is the worst enemy of her son’s
kingdom.”
“I wish I could trust you!” she cried with a gasp. “But no, you
must have some other motive. You could not endure her coldness,
her childish peevishness, her foolish little affronts, as you do, unless
you had some end in view.”
“My end is solely to see King Michael seated safely on his
father’s throne, Fräulein. I have given up my life first to Otto Georg
and now to his son, and it strikes one as a little hard that the
sacrifice should be supposed to be made for the sake of some
personal advantage. If you can suggest one, I should be glad to
hear it, for I confess it has occurred to me more than once that I am
wasting my pains on an ungrateful family.”
“I long to believe you,” said Fräulein von Staubach. “I might be
able to make your path easier, but how can I, knowing what I know?
I remember you of old—your intrigues, your deceptions, all the
course of trickery you carried on when your brother was King. I do
not—I cannot—believe that you have really changed.”
“Perhaps, Fräulein, you will believe in my disinterestedness
when the kingdom is ruined in spite of my best efforts. Pray don’t
misunderstand me. I am not uttering any threat, for I shall continue
to do my best for the King, for his father’s sake. But I cannot hope
to succeed, and you know to whom my failure will be owing.”
“I wish I could trust you!” she said again, as she passed out of
the door he held open for her, and Cyril went back to his desk well
pleased.
“Now she is divided in mind,” he said to himself. “The new light
is beating fiercely on all her preconceived notions of a martyr Queen
persecuted by a revengeful Minister. She will do all she can to
reconcile the two views, and meanwhile she will improve matters a
little.”
And Cyril turned his attention to other subjects, feeling perfect
confidence in his new agent. It was no surprise to him a few days
later to receive a visit from Mrs Jones, who entered the office with a
face wreathed in smiles.
“You’ll be pleased to hear as I’ve changed my mind about goin’
home, my lord,” she said. “I hope as your lordship haven’t give
yourself no trouble about findin’ out trains for me?”
“I am extremely glad to hear this,” returned Cyril. “You decided
that you had been a little too hasty, I suppose?”
“No, my lord, that I never will give in to. Them as was hasty has
made amends, as was proper. Her Majesty come into my nursery
this mornin’, and I stood up very stiff-like, as my feelin’s bein’ hurt.
But she speaks to me very pleasant, and says, says she, ‘Mrs Jones,
I spoke hasty to you a short time ago, and it may be that through
ignorance of your language I said more nor I meant. I hope very
much that you have made no other arrangements, and will stay with
us. I ask it as a favour to myself, and also to the King, as will break
his heart if you leave him.’ There, my lord! I was all in a flutter to
think of a crowned Queen talkin’ to me of favours, and the little King
come runnin’ and says, ‘Nursie not goin’ away. Nursie stay and tell
stories,’ and I burst out cryin’ like any old crocodile, as they say, and
told the Queen that my heart was just about broke to think of
leavin’, and that I asked no better than to stay. And this afternoon
her Majesty have sent me a beautiful gown-piece of black silk, that
thick you might use it for a parachute if you wanted to, and so I’ve
took back my notice, my lord.”
This was extremely satisfactory so far as it went, but Cyril was
not long in discovering that the part he had played with respect to
Mrs Jones’s remaining a member of the royal household was not
appreciated by the Queen. It was tolerably clear that Fräulein von
Staubach had repeated verbatim, or, at any rate, rather in an
exaggerated than a diminished form, the conversation she had held
with him, and that the Queen had taken it to heart. She was very
careful in these days to entrench herself behind an impassable
barrier of etiquette, and she indulged in no freaks and no outbursts
of temper, while yet she kept Cyril at a distance, and made it evident
that he was in disgrace. This little exhibition of spite could do Cyril
no harm, for he still held the reins of authority and controlled the
purse-strings; but it was a very uncomfortable state of affairs for the
other members of the Court, who were obliged to do their utmost to
keep in favour with both parties. In these circumstances, Cyril
thought it a suitable opportunity to ask for a few days’ leave of
absence in order to pay his projected visit to Bellaviste, and the
permission was granted with a most unflattering readiness, which,
however, only caused him amusement.
“I don’t think she’ll be up to much in the way of tricks while I’m
gone,” he said to himself; “this last pulling-up has taken her rather
aback. She must know that I shall hear of all that goes on, and hurry
back if there is anything wrong. I don’t really like going, and yet I
must have a word or two with Drakovics. He shall learn to
understand that our partnership is not to be all on one side. If he is
not going to back me up, he may look out for some one else to pull
the chestnuts out of the fire for him. And I’m not sorry to have a
little change from this wretched place. I wonder whether there
would be time to run up to Vienna for a day or two? Oh no; my
precious charge would be getting into mischief, and, after all,
Bellaviste is better than this dull hole. Nothing much can happen in
five days. The servants know that I am master, and Stefanovics and
the Baroness will keep me posted up. If any one launches out on the
strength of my being gone, I shall be able to deal with them when I
come back.”
But on the day before that fixed for his departure, he discovered
that his authority in the household was not quite so firmly rooted as
he had imagined. It happened that in the course of the morning a
telegram arrived for him, and was brought into his office by one of
the royal footmen. The telegram was of little importance, but
something unfamiliar in the aspect of the bearer struck Cyril.
“Wait a minute,” he said, as the man was leaving the room.
“How is this? You are not Alexander Sergeivics, but Peter, and you
were one of the servants left at Bellaviste to look after the Palace.”
“Yes, Excellency; but my brother’s wife is dangerously ill at
Bellaviste, and I am taking his place that he may be with her.”
“Indeed! an excellent arrangement; but you will have to learn,
and so will your brother, that servants in the royal household are not
at liberty to exchange their posts to suit their own convenience.”
“Not if they have her Majesty’s sanction, Excellency?” There was
triumph clearly visible under the man’s deferential manner.
“Her Majesty’s pleasure overrides all regulations, of course. I am
to understand that your brother obtained her consent?”
“It is so, Excellency. Having obtained leave of absence, I came
to Tatarjé to tell my brother about his wife, and her Majesty, on
hearing the news, granted him permission to return to Bellaviste
immediately. When my brother ventured to suggest that it was
requisite for him to obtain leave from your Excellency, her Majesty
was pleased to say, ‘What has Count Mortimer to do with it? I have
told you to go, I the Queen. That is enough.’”
“Quite enough,” returned Cyril genially. “Ask M. Paschics to step
this way, and to bring with him the household book. The change and
the reason for it must be entered.”
The man departed, and Cyril walked to the window.
“There’s something fishy about the business,” he said; “but the
Queen has made it next to impossible to clear it up. I am pretty sure
I remember that there was something suspicious about this man
Peter. Come in, Paschics.”
M. Paschics, who entered in response to the invitation, was
ostensibly Cyril’s most confidential clerk, and there were only a few
who knew that he was in reality a member of the Secret Police,
specially detailed to watch over the royal household. The book which
he brought with him was to all appearance merely a record of the
comings, goings, and conduct of the domestics attached to the
Court; but by means of a series of private marks, the meaning of
which was known only to himself and Cyril, it contained also an
account of their political opinions and personal histories.
“You have heard that Peter Sergeivics is at present taking his
brother’s place,” said Cyril. “Turn up his name, and let me see what
there is against him.”
“He is a member of the Golden Eagle Society for the study of
Scythian literature, your Excellency, and has been heard on several
occasions to express approval of the sentiments uttered on St
Gabriel’s day by his Beatitude the Metropolitan.”
“I knew there was something wrong. Those literary societies are
invariably political clubs in disguise. Well, Paschics, this man is to be
watched. Notice his resorts and his associates, and let me know the
result of your shadowing.”
“Yes, your Excellency. He is not on duty this afternoon and
evening, and I hear that he is going into the town. As a stranger, he
wishes to see what the place is like.”
“And very natural too. If he finds any friends here, it is as well
that we should know it. That is all for the present.”
Paschics retired, and Cyril returned to his accounts. Later in the
day he was witness of a curious little incident which he did not at
the time connect with Peter Sergeivics and his suspicious record, but
which proved afterwards to have a bearing upon it. Standing at a
window which overlooked the approach, Cyril saw, to his
astonishment, the O’Malachy advancing to the door of the Villa. His
clothes were faultless, his moustache waxed; there was something
jaunty about his very limp. A stranger would have taken him for a
prince travelling incognito, or at the least for an exquisite of the
Pannonian Court; and Cyril, who knew him only too well, wondered
what on earth he was up to now. The door of the room was slightly
ajar, and he heard the familiar voice, with its rich rolling intonation,
asking leave to see over the Villa. The obvious answer was returned
that sightseers were not admitted at present, to which the
O’Malachy appeared to reply by producing the local guidebook,
which mentioned that visitors were allowed to go through the State
apartments on two days in the week. On being assured, however,
that this did not apply to the times at which the Court was in
residence, he perceived his error, and retired, with profuse
apologies, to view the Villa from the gardens, admission to which
was practically unrestricted.
“Pretty cool cheek of him to come here!” said Cyril to himself. “I
wonder he didn’t make use of my name as a reference. Now, what
was the object of this, I should like to know?”
But his curiosity remained unsatisfied, and he thought no more
of either the O’Malachy or Sergeivics until Paschics presented himself
as soon as he entered his office the next morning. A glance at the
detective’s face showed Cyril that he was bubbling over with news,
and he looked about for eavesdroppers, and made sure that the
door and windows were shut, before he would allow him to tell his
tale.
“According to your Excellency’s orders, I shadowed Peter
Sergeivics yesterday,” began Paschics. “In the afternoon I saw him
leave the Villa by the servants’ entrance, and take the road to the
town. While still in the grounds, however, he was met by an elderly
gentleman of military appearance, walking with a slight limp.” Cyril
uttered an exclamation. “As your Excellency has surmised, I
recognised this person as the Scythian officer who was arrested by
mistake some time ago, and set at liberty immediately afterwards.
Perceiving by his livery that Sergeivics belonged to the household,
he stopped him, and apparently requested him to point out to him
the principal architectural features of the Villa; for Sergeivics gave up
his intention of proceeding to the town, and escorted him round the
gardens, exhibiting the chief points of interest. I must confess with
regret that I could not succeed in following them sufficiently closely
to hear their conversation. At last Colonel O’Malachy presented
Sergeivics with a handsome pourboire, and departed. I discovered
afterwards that he had tried to gain admission to the interior of the
Villa, but had been refused an entrance.”
Cyril nodded. “I saw that myself,” he said.
“After this, your Excellency, Sergeivics returned to the servants’
quarters, and did not go out again until the evening. Following upon
his steps, I tracked him to a tavern in a low part of the town. Having
seen him seated at one of the tables, I hurried to the lodging of an
acquaintance of mine near at hand, and borrowed from him the long
coat, high boots, and fur cap of a droschky-driver. With the aid of
the wig and false beard which I always carry about with me, my
disguise was complete, and I entered the tavern and sat down at the
same table as my quarry. I then noticed that the table was close to
the end of a passage, in which was a door. From time to time one of
the men in the room would enter the passage and disappear
through the doorway. Again, several persons came in one by one
from the street, and, believing themselves unnoticed, also slipped
through. Among these, I am certain, was Colonel O’Malachy. He was
disguised in a country cloak and cap; but I could not mistake his
limp, nor his white moustache. I observed that all who passed in at
this mysterious door were subjected to some test. They knocked, I
think, in a peculiar scraping manner; but I cannot be sure of this,
owing to the distance and to the noise around me, and also to the
necessity of not appearing to watch too closely. Moreover, certain
questions, which also I could not hear, were asked and answered
before the door was opened. Then, as it seemed to me, a badge of
some kind was exhibited, which was worn on the under-side of the
left-hand lapel of the coat, and admission was immediately granted.
All this time, your Excellency, I was behaving as though I had
already drunk too much brandy, and offering to treat Sergeivics and
the other guests. The Thracians, as your Excellency knows, do not
become hilarious when excited by liquor; but I was talkative and
inclined to be quarrelsome. Sergeivics tried to shake me off, and
when he thought he had directed my attention to a group of fresh
arrivals, rose and endeavoured to slip down the passage. But I
caught him by the coat, and said in a drunken voice, ‘Not so fast, my
friend. There seems to be something interesting going on in there,
and I should like to come too.’ He looked at me as though he could
have killed me, but bent over the table and fixed me with his eye.
‘Look here,’ he said, ‘I have no business to tell you what it is; but
you have been so liberal with the brandy that I don’t mind letting
you know in confidence. You have heard of the Freemasons?’ ‘Oh
yes,’ I said; ‘they worship the devil, and their rites are proscribed.’
‘Stuff!’ he said; ‘that is what the priests tell you. Count Mortimer
himself is a Freemason, and therefore the police have orders to wink
at their doings, in spite of the law. This is one of their lodges, and I
am a member, so you see I can’t take you in, much as I should like.’
I gave a tipsy grunt, and let him go, when he vanished down the
passage at once. I sat there some time longer, talking and treating,
and saw other people go in, some of them officers, as I knew by
their walk, and others, I am sure, priests. Then, fearing to arouse
suspicion, I staggered out, and, taking up a position from which I
could watch the place, tracked Sergeivics back to the Villa about an
hour and a half later. That is my report, your Excellency.”
“And a very good one it is. I shall require you again presently,
Paschics. You can go now, and tell Sergeivics that I want him.”
“But your Excellency does not intend to tax the man with his
treachery? He will be desperate—and he is probably armed.”
“So am I,” was the brief response; and Paschics retired. When
Sergeivics entered the room, Cyril was seated at his writing-table,
looking for something in one of the drawers.
“Ah, Peter Sergeivics—wait a minute,” he said, glancing up. “By
the way, what’s that on the left-hand lapel of your coat?”
The man’s face turned pale, and his hand went up in a terrified
snatch. Finding nothing, he recollected himself immediately.
“Perhaps you will kindly tell me what is wrong there,
Excellency?”
“Nothing—now,” responded Cyril; “but something very wrong
was there last night.” There was a sudden movement of the
footman’s arm, but Cyril was too quick for him. The right hand which
had been hidden in the drawer came up suddenly, holding a revolver.
“Throw up your hands this moment, and stand where you are, or
you are a dead man!” were the words which smote upon the ear of
the astonished Sergeivics, as he found himself covered by the
weapon.
“You will not murder me, Excellency?” he faltered.
“Not on any account; but I shall have no compunction in killing
you in self-defence. Peter Sergeivics, you came to Tatarjé under the
orders of a revolutionary committee, charged to help them in
carrying out their schemes. By an ingenious device, you obtained an
opportunity for receiving orders from the Scythian agent here and
furnishing him with information. Last night you attended a meeting
at which the final plans for the outbreak were agreed upon, and the
parts to be played by the various conspirators assigned to them.”
“What does your Excellency want with me?” whined the luckless
man.
“I want nothing, as you see. If you care to offer any
information, the fact will be taken into account in deciding your
sentence. If you do not, you will merely be dismissed from the royal
household, and it will become known that you have retired with a
pension, awarded in consideration of the loyal assistance furnished
by you to the Government, which has led to the detection of the
plot.”
Sergeivics writhed. “You know that I should be dead within an
hour, Excellency,” he whimpered. “If I tell you all I know, will you
guarantee that I shall be saved from the vengeance of the rest?”
“Stay where you are, if you please,” as the wretched man made
a movement as though to throw himself at Cyril’s feet. “It will be just
as uncomfortable for you to be shot by me as by your fellow-
conspirators. I have said that I do not ask you for information; but if
yours should prove to be of any value, I will guarantee that you shall
be sent to Bellaviste under a sufficient escort to protect you from the
vengeance of your friends. This is showing quite undeserved mercy
to one who has deliberately plotted to murder the Queen and the
young King——”
“Never, Excellency! There was no thought of murder. We merely
——”
“Ah, your information differs from mine, then?”
“Your Excellency must have been misinformed. Our object was
simply to secure the persons of the King and Queen, and to induce
the Queen to consent to the King’s conversion to the Orthodox faith.”
“To induce her? yes. And when persuasion failed——?”
The man’s face grew pale again. “There was something said
about a few days without food for the Queen, and the knowledge
that her child and attendants were suffering in the same way,” he
muttered.
“Exactly; and what would that have meant but murder, in the
case of delicate women and a child? And this precious scheme was
to be carried out to-night, was it, that you might have at least three
clear days before I should begin to feel surprised at receiving no
news from Tatarjé? or perhaps you would like to set me right on this
point also?”
“No, Excellency; your information is correct.”
“And the plot is supported by the garrison, the Church, and the
townspeople, headed no doubt by the mayor?”
“Yes, Excellency; and as you know, of course——”
“Yes, I was waiting for this. By whom besides?”
“I—I fear your Excellency knows more than I do. The message
which the head of our circle at Bellaviste gave me to bring here was
merely that a certain person was propitious, but must not be too
confidently relied upon.”
“Take care. To whom did you understand that message to
allude?”
“To—to the Metropolitan, Excellency.”
“You are telling me lies.”
“No, no, indeed, Excellency. I will swear it by the Holy Fire, by
all the saints! We of the lower levels are not admitted into the
possession of important secrets, but we conjectured among
ourselves that the Metropolitan was meant.”
“Well, be careful. To continue: the King and Queen were to be
imprisoned in the Bishop’s Palace, which is capable of standing a
siege; and when the conversion was effected, the Queen was to be
further compelled to place the kingdom under the protection of
Scythia, and request the favour and support of the Emperor?”
“Yes, Excellency.”
“And if by any chance I did not start to-night for Bellaviste, I
was to be killed?”
“That is only natural, Excellency.”
“Quite so. Well, I will take you with me to Bellaviste when I start
to-night.”
“You start to-night, Excellency? But—the station is watched.
Their Majesties will not be allowed to travel.”
“That need not interfere with my journey. I have unmasked
plots before this one, my friend. You see this cigarette-case with the
monogram in brilliants? I will place it on the edge of the table close
to you. Lower your left hand—be careful, I am ready to shoot—take
the case, and put it in your right-hand outside pocket. You
understand? Good.”
He rang sharply the bell which stood on the table, and Paschics
burst open the door and rushed in, followed by two or three
servants, and pausing in astonishment when he saw the tranquil
condition of affairs.
“I must have this man searched,” said Cyril. “I suspect him of
being in possession of the cigarette-case presented to me by the
Emperor of Pannonia, and bearing his Majesty’s cipher in brilliants. It
is possible that you may find other stolen property upon him as well.
I missed one of my revolvers the day before yesterday.”
In an instant Sergeivics was seized and held by two footmen
while Paschics searched his pockets. The cigarette-case and a
revolver were produced almost immediately, and laid in triumph on
the table; but nothing else was revealed by the search. Cyril nodded
pleasantly.
“I thought so,” he said. “Well, it is quite out of the question that
I should postpone my journey on account of this, and therefore the
man had better be taken to Bellaviste to-night by the train in which I
shall travel. Instruct the police to provide a proper guard, M.
Paschics, and report to me when you have made arrangements.”
CHAPTER X.
A NEW RELATIONSHIP.

Left to himself, Cyril rose from his chair, and began to walk rapidly
up and down the room, maturing some plan in his mind as he
walked. Once or twice his meditations were interrupted by the
entrance of a servant with a letter or a message; but he disposed
quickly of these stray pieces of business, and returned to the
consideration of his more important scheme. When Paschics came
back, he sent him to summon M. Stefanovics, and then unfolded to
the two men the tale of the conspiracy which he had forced from the
wretched Sergeivics.
“But this is fearful!” cried M. Stefanovics. “Surely you have taken
some steps, Count? Their Majesties ought to have left the town
already.”
“The railway-station is watched, and even if it was too early to
oppose the departure of the Court by force, nothing could be easier
than to wreck the train,” said Cyril curtly.
“But why not telegraph for help to Bellaviste—or to Feodoratz, if
M. Drakovics is too far off to be of any assistance?”
“Because I have for some time past suspected that some one
was tampering with our telegrams, and now I am sure of it. I have
just received a telegram which ought to have reached me three days
ago, but which the operator says must have been delayed in
transmission. It is from M. Drakovics, begging me not to leave
Tatarjé until I have heard again from him, and if it had arrived in
proper time it would have delayed my journey. Now, of course, it is
too late.”
The eyes of the other two men met with a puzzled expression.
“But if you suspect the officials here,” suggested M. Stefanovics,
“why not despatch a telegram from some point outside the city?”
“Because the danger does not arise merely from treachery here.
That would scarcely explain the delay in this telegram, and certainly
not the confusion and omissions which have puzzled me in others.
No; I believe that the conspirators are in the habit of tapping the
wires between this and Bellaviste, and so reading, and occasionally
altering, the telegrams which pass between the Premier and myself.”
“Then, you consider, Count, that to telegraph for assistance
would simply defeat all our hopes of catching the miscreants
unawares?”
“Exactly. Whatever is to be done must be done from this end.”
“You would perhaps suggest that their Majesties should cross
the frontier, and take refuge in Dardanian territory?”
“No. I had thought of that at first; but besides producing an
extremely unfortunate impression abroad, the attempt would be
useless, for the Prince and Princess have left their country residence,
and returned to Bashi Konak for the opening of the Legislature.”
“But still, would it not be advisable for their Majesties, under the
pretext of a simple drive, to cross into Dardania, and then to make
all speed for Bashi Konak?”
“It might be, except that everybody in the Villa and the town
knows that no one belonging to the Court will drive to-day. You
cannot surely have forgotten that the Queen is commemorating the
late King’s birthday in retirement in her own apartments? If orders
were given to prepare a carriage, it would instantly be surmised that
something alarming had occurred, and a small band of resolute men
could easily stop us at a dozen points between this and the
Dardanian frontier. Moreover, we must not forget that the relations
between the Scythian and Dardanian Courts are very close, and to
my mind the message brought by this man Sergeivics to his fellow-
conspirators here points to some knowledge of the plot on the part
of Baron Natarin, if not of a more exalted individual behind him. It
might even be a portion of the design to drive her Majesty into
seeking refuge in Dardania.”
“One must hope,” said M. Stefanovics, with some pique, “that
you have some plan of your own to propose for securing the safety
of their Majesties, Count, since you see so many flaws in all that I
can suggest.”
“Exactly; I have a plan—but I know that you will see
innumerable flaws in it, although it is the only one that seems to me
to offer a hope of success.”
“If it commends itself to your Excellency,” said Paschics stoutly,
“that is enough for me.”
M. Stefanovics gave a nod of acquiescence, and Cyril brought
out a map of the district and unrolled it. “You perceive,” he said,
“that in this case the railway and the telegraph, instead of being, as
usual, our friends, are our enemies, since they are in the power of
the conspirators. My idea is, then, to avoid them altogether, and
provide a means of escape for their Majesties by way of the old
post-road, which takes quite a different route from the railway, and
reaches at last the estates of Prince Mirkovics, whose loyalty no one
can doubt, and who will provide us with a safe asylum until help can
be obtained from Bellaviste.”
“But you forget, my dear Count, that spring can scarcely be said
to have begun, and that the post-road passes through the forest and
across the mountains before it reaches the Mirkovics domain.”
“I do not forget it; but this is a matter of life and death,
Stefanovics.”
“But surely the presence of so large a body of travellers on the
old road would create such a stir that it would be impossible for the
Court to travel unnoticed, not to mention the difficulty of providing
transport for so many?”
“You are right, and delay or recognition would simply mean that
we should be pursued and brought back. No; I do not intend to
conduct a Court progress, after the manner of a second flight to
Varennes. My idea is simply that M. Paschics and I should smuggle
the Queen, the little King, and one lady-in-waiting, through the
country in disguise.”
The audacity of the proposal took away M. Stefanovics’s breath.
“And the rest of the Court?” he inquired blankly.
“I am afraid they must stay here, in blissful ignorance, until the
escape of their Majesties is discovered. The conspirators are not
likely to be bloodthirsty, except in the case of unfortunate suspects
like myself.”
“We are to remain at the Villa, while you and the Queen—Holy
Peter! do you imagine the Queen would ever consent to such a plan
of escape, Count?”
“I trust she may, if it is put before her suddenly. If she had time
to think over it, I agree with you that there would be no hope. You
see how the thing works out. I must pretend to start for Bellaviste as
I had arranged to do, in order to avert suspicion; but you must let
me into the Villa again by the private stairway. Then we must lay the
matter before the Queen, and prevail upon her to start at once. We
can only count on being left in peace until the time when the Villa is
usually quiet for the night.”
“The risk is terrible. And yet, what else——? But you will never
obtain her Majesty’s consent.”
“Then her Majesty will have the pleasure of seeing me shot
down before her eyes, I presume. But do you agree to the plan in so
far as you are concerned?”
“How can I venture to object to it? It seems the only hope, and
you are risking more than the rest of us. A few days’ imprisonment
would be the worst punishment we should receive. But the hardships
of your journey will be dreadful for women and a child.”
“Better than the dungeons of the Bishop’s palace—that is all one
can say. The season is altogether on the side of the conspirators.
Then you will come into the scheme, Stefanovics? Now, Paschics, for
your part. You have some relations living not far off, I believe?”
“Yes, Excellency; a married brother, who farms his own land.”
“And you did not go to see them at Christmas, I think? Well, it
will be convenient if you pay them a visit to-day. Start after lunch,
and take a bag—full of presents for the children, or delicacies from
the town, or anything of the sort. You may let it be known that you
will not be back to-night. At your brother’s, hire his lightest cart, with
the two best horses he has, and tell him he will find it the day after
to-morrow left for him at No. 4 posting-house on the old road to
Bellaviste. Put in some straw—as much as you can—and any rugs
you can get to make it comfortable, and as soon as it is dark this
evening, drive the cart to the spot where the corner of the Alexova
estate touches the old road. Wait there under the trees and give
your horses a good feed. If we succeed we will join you; if not, you
had better get back to your brother’s as fast as you can, for your
own sake. By the bye, could you disguise yourself as a courier?”
“With the greatest ease, your Excellency.”
“Then take with you anything you will require. You will be
wanted to-morrow as courier to an English family whose carriage
has met with an accident. I will see about the passport.”
“One moment, Count,” said M. Stefanovics, with some
embarrassment. “I do not wish to interfere with your excellent plans;
but you are, after all, a young man and unmarried. Would it not be
more suitable—less open to unfavourable remark—if Madame
Stefanovics and I undertook the responsible task of conducting her
Majesty’s flight, in conjunction, of course, with M. Paschics?”
“It would simply be putting my neck in a noose,” muttered
Paschics, gazing apprehensively at the placid face and comfortable
girth of the worthy chamberlain.
“I have no objection whatever,” returned Cyril. “You must see
for yourself that I risk my life in coming back at all, and the slightest
misfortune or accident might lead to our being hunted down like
wolves. By all means carry the thing through, Stefanovics. No doubt
you have more influence than I have over the Queen, who is not
exactly the easiest of ladies to manage.”
“True,” remarked M. Stefanovics sadly. “Count, I have done you
an injustice. You alone can carry out this scheme, if any one can do
it. I will not venture, for I should only fail, and do harm to others.”
Cyril laughed silently to himself as the two men left the room,
and then turned his attention to arranging several matters of
importance connected with the great scheme. It was necessary first
to write to M. Drakovics; but when the letter was finished he put it
into his pocket, and did not post it. Next he busied himself in
drawing up a passport for the party of English travellers of whom he
had spoken to Paschics, and who comprised a Mrs Weston, her
brother, her little son, her nurse, and an Italian courier. The
document did not leave Cyril’s hands; but when he had finished with
it, it bore other signatures than his, carefully copied from a genuine
passport which lay before him on the table. There was one thing
which he did not attempt to imitate—the stamp of the frontier
official whose duty it was to see that all passports were in order.
Cyril had not a stamp at hand, and it would risk suspicion, and
certainly cause delay, to send for one, while a bad imitation might
arouse doubts as to the genuineness of the whole thing. It went to
his heart to set out with the document incomplete; but he knew that
it is sometimes necessary to sacrifice technical perfection to practical
utility, and after drying his handiwork carefully in the sun, he put it
by safely. He had intended after this to take advantage of Dietrich’s
absence at dinner to go to his own quarters and pack a small bag
with necessaries, hiding it in his office, where the valet would not be
likely to find it; but he decided that it was improbable he would be
able to carry it, and contented himself with putting two or three
indispensable articles in his pockets. There were still various things
to be arranged in view of his impending departure, and he spent the
afternoon in attending to these. He had his farewell audience of the
Queen, dined with the household, and drove to the station with
Stefanovics, who was deputed to see him off. There were several
dignitaries on the platform, who had come for the same purpose—
the mayor of the town, the commandant of the garrison, an
archdeacon to represent the Bishop, and one or two others. It was
only right that they should be there; but Cyril felt sure that some of
them would have found excuses and stayed away if it had not been
that they were eager to assure themselves of his departure by the
evidence of their own eyes. He stayed on the platform talking to
them for some minutes, and then entered his carriage, which was
one of those belonging to the royal train, but had been detailed for
the service of the Minister of the Household.
“It’s a blessing all that fuss is over!” he said aloud, as the door
was shut after he had shaken hands with the officials outside. “Now
that we are left to ourselves, Dietrich, I think I will change my
things. What is the good of a holiday if one doesn’t wear holiday
clothes?”
To Dietrich, who knew that his master shared the
incomprehensible dislike of most Englishmen for livery of any kind, it
was quite natural that he should be anxious to change his official
uniform at once for a suit of ordinary clothes, and the transformation
was quickly effected and concealed by the regulation overcoat which
had been worn in driving to the station. It was well that this
precaution had been taken, for before long a sudden hubbub arose
on the platform, followed by a visit of the mayor to the carriage.
Sergeivics, with his escort of police, had just been conducted to a
third-class compartment, and the gentlemen on the platform were
anxious to know of what crime he was accused. Happily Cyril was
able to gratify their curiosity by a vivid description of the theft of the
cigarette-case, aggravated, as it was, by the possession of the
revolver, which had, no doubt, also been purloined, and his account
interested them so much that they all crowded into the carriage to
hear it. Cyril began to fear that they would insist on travelling with
him as far as the next station, which would have complicated
matters seriously; but it was as important for them to be in Tatarjé
that night as to see him out of it, and they returned to the platform
precipitately when the bell rang. The moment for Cyril’s great coup
was close at hand; but there was not the slightest trace of
excitement visible in his manner as he stretched himself in an arm-
chair, and raised his arms behind his head in a long yawn.
“I shan’t want you any more to-night, Dietrich; and don’t come
bothering me at every station. Get a good night’s rest; I shall ring
fast enough if I want you. And, by the bye, if I don’t call out to you
when we get to Bellaviste in the morning, don’t come in and wake
me. See that the car is shunted into the siding, and take this letter
straight to his Excellency the Premier. You understand? You are not
to lose a minute. Then go home: if I have got there before you, it
will be all right; if not, wait for orders. You can go now.”
But Dietrich had failed fully to comprehend the order, and it was
necessary to repeat and emphasise it, so that the train was already
in motion when he betook himself to his own compartment. Cyril,
who had drawn up one of the blinds, and was bowing his farewells
to the group on the platform, turned with a sudden quickening of
the heart as he heard the door shut behind the valet. The speed was
increasing; in another moment his time for action would come. He
threw off his overcoat, and felt mechanically in his pockets to see
whether he had transferred to them everything he wanted. The train
moved slowly out of the lighted station into the dark night, and Cyril
opened the door of communication, and stepped out on the
gangway between the two carriages. Climbing over the railing, he
remained for a moment holding to its outer edge, then let himself
drop. He fell clear of the line, and rolled out of the way of the train,
remaining prostrate at the side of the road until the last carriage had
passed, then climbed the bank (the station stood outside the town),
and plunged into the wood which fringed it. He had studied his route
carefully on the map, and carried a compass on his watch-chain,
which he consulted every now and then with the help of a match, so
that he succeeded in making his way safely round the outskirts of
the town without approaching any house. He was tired, wet, and
muddy when he reached at length the wall which surrounded the
grounds of the Villa, and he felt it to be an additional grievance that
he failed to strike the gate exactly, and had to make a considerable
circuit before he came to it. The gate was reached at last, however,
and it responded easily and noiselessly to the well-oiled key which
he took from his pocket. Crossing the grounds, he came to the
shrubbery opposite the terrace, and for some few minutes watched
the sentry pacing up and down. Then there came the sound of the
opening of a door, and the little red ball of light from a cigar became
visible. This was the signal which Cyril had agreed upon with
Stefanovics, and the next time that the sentry’s back was turned he
crept across the terrace, and arrived in the doorway so suddenly as
to startle the chamberlain almost into a cry. Leaving the door ajar,
they crept up the narrow winding staircase on which it opened, and
which was a relic of the days of the last king of the house of Franza.
It communicated with a room which had been used by King Peter for
receiving his Ministers—and other persons—and which now served
the Queen for holding private audiences. She disliked the secret stair
on account of its associations, and had wished to have it bricked up;
but Cyril had succeeded in persuading her that it was an interesting
historic survival, and might possibly prove useful again, little thinking
how soon he was to discover the truth of his own words. One of the
only two keys which fitted this door was in his possession by virtue
of his office, and the lock moved easily.
“Ask to speak to Baroness von Hilfenstein,” he whispered to
Stefanovics, as the latter preceded him into the room; “but on no
account let out that I am here until you are sure that no one else
can hear what you have to say.”
He waited in darkness behind the partially closed door until the
sound of voices showed him that Stefanovics had succeeded in
finding some one; but still he was not summoned, and time was
flying. Pushing open the door, he appeared in the room, to the
accompaniment of a little scream from the Baroness, and an
outpouring of self-justification from Stefanovics.
“The Baroness refuses to admit us to her Majesty’s presence,
Count, although she tells me that the Queen has sent away her
maids, and is talking over the fire with Fräulein von Staubach. It is in
vain that I——”
“Consider the hour, my dear Count,” said the Baroness
reprovingly. “I must beg of you to retire immediately. It is in the
highest degree irregular for you to seek an audience of the Queen at
such a time.”
“My dear Baroness,” returned Cyril, “you know me pretty well by
this time, and will believe me when I tell you that my business is of
such importance that if you won’t consent to inform her Majesty of
my desire to see her I must announce myself.”
After a glance at his face to assure herself that he was in
earnest, the Baroness withdrew without a word, and the next sound
that reached his ears was the Queen’s voice in the adjoining room.
“Count Mortimer here again? I thought we were free from him
for a week at least! He asks to see me at this hour? The man must
be mad. Most certainly I refuse to see him, Baroness. Be so good as
to tell him that I shall know how to resent this intrusion.”
A low-toned remonstrance from the Baroness and a frightened
murmur from Fräulein von Staubach followed, interrupted ruthlessly
by Cyril.
“Madame,” he cried, approaching the door of communication, “I
have returned at the risk of my life to bring you news of a plot which
aims at the forcible conversion of your son to the Orthodox Church,
and the subjugation of his kingdom to Scythia.”
“A plot to convert my son!” The door was thrown open, and
Cyril had a momentary glimpse of a figure with terrified dark eyes,
and rippling chestnut hair flowing over a white dressing-gown. Then
the Baroness dashed forward, shutting the door in his face, and he
heard her agonised voice—
“Madame, remember your position! I entreat your Majesty——”
The rest was inaudible, and Cyril stood fuming over the precious
time which was being lost because the old woman would not allow
him to see the Queen in a dressing-gown. But the door opened
again almost immediately, and the Queen stood on the threshold,
pale and calm. The other ladies had clad her in a loose black gown,
and hidden away her hair under the flowing crape veil she wore in
the daytime, and she looked a different being.
“Tell me, Count,” she said, “when is this plot to be carried out?”
“To-night, madame; and I believe very shortly. You and the King
were to be seized in your beds and carried off to the Bishop’s palace,
there to be starved into compliance with the demands of the
conspirators.”
“And you would advise us, no doubt, to take refuge in the castle
immediately?”
“I fear, madame, that you would only be running into danger.
The garrison is honeycombed with disaffection.”
“Then there is only one chance left, for I know well that it is
impossible to defend this house. We must go to the municipal
offices, and throw ourselves on the protection of the burghers.”
“Unfortunately, madame, there is no safety there. The whole of
Tatarjé is utterly disloyal.”
“Then what are we to do?” Her voice rang piteously in his ears;
but she dashed the tears resolutely from her eyes. “Count, I rely
upon you to help me. This plot threatens my son’s honour—not only
his kingdom. You have not come here simply to warn us of the
approach of inevitable danger. You have a plan to save the King. Tell
me what it is. I will follow your advice.”
She had risen so completely above her usual level that for the
moment Cyril was tempted to forget her inveterate distrust of him.
He answered promptly—
“There is one way to save the King and yourself, madame. If
you will consent to adopt a disguise, and to start immediately upon a
somewhat troublesome journey, with your son and one lady in
attendance, I will do my best to conduct you safely to Bellaviste.”
“Ah! you have made plans for this journey?”
“One does not generally undertake such a venture at
haphazard, madame. I have done what I could to ensure success,
and I may say that I have good hopes of attaining it.”
“And what,” she demanded, in a voice that made him jump, “is
there to assure me that this is not a plot of your own, invented for
the purpose of making me ridiculous or even humiliating me in the
eyes of the world? Where are the proofs of the conspiracy you have
discovered?”
“I have none,” said Cyril laconically. Her change of tone had
restored his mind immediately to its usual balance. “If you will wait
half an hour or so, madame, the proofs will probably arrive in the
persons of the conspirators; but it will then be too late to save your
son.”
She bit her lips with vexation. “It is useless to ignore the fact,
Count, that the relations between us have not been wholly amicable
of late, and you are popularly supposed never to let slip an
opportunity of revenging yourself.”
“A guilty conscience is usually an unpleasant companion,
madame; but on this occasion it is also an untrustworthy adviser.”
“How? Do you venture to imply—— You must be aware that you
are asking me to repose an extraordinary degree of confidence in
you, Count.”
“Not more than your husband reposed in me, madame. Have I
ever betrayed that confidence? Even when you most disliked my
measures, have they not proved to be advantageous—even
necessary?”
“Unhappily they have. But this case is wholly without
precedent.”
“It is for you, madame, to decide whether you prefer to be
saved in an unprecedented way, or ruined in a manner which is
unfortunately not entirely new. If your son is to be rescued, I must
ask you to make up your mind quickly now, and to be obedient
afterwards.”
“Obedient! That is a strange word to use to me!”
“I have no doubt that the action is equally new to you,
madame.”
She turned from him with a gesture of disgust. “How am I to
decide?” she asked angrily. “On the one side I risk my son’s
kingdom, on the other my good name. If I could only trust him!
Baroness, I will not appeal to you. If Count Mortimer suggested a
journey to the moon, you would only inquire mildly, ‘By what route
does the Herr Graf propose to conduct us?’ Sophie, you are not a
blind idolater. Tell me quickly—shall I trust him?”
Poor Fräulein von Staubach, finding herself thus appealed to,
turned first red and then white, twisted her fingers painfully
together, and sought inspiration in the corners of the ceiling. Her
advice came suddenly, accompanied by a rush of tears and a great
gulp: “Trust him, madame. I believe you may.”
“Then you also have gone over to the enemy!” said the Queen
sarcastically, as she turned again to Cyril. “I congratulate you upon
your convert, Count. I wish you would exercise the same influence
over me; but as you have not thought fit to do so, I am afraid I must
ask you to swear that you have told me nothing but the truth, and
that your motives are what you represent them to be. Will you do
this?”
“No, madame, I will not swear. If you cannot accept the word of
a man who has endangered his life in order to serve you, you must
drag him down to destruction with yourself.”
She looked up in alarm, and caught sight of the repressed fury
in his face. She gave a little gasp, and her eyes fell before his.
“Forgive me, Count. I do trust you. I will obey.”
Cyril’s heart leapt within him, but he betrayed no sign of
exultation over his victory. His tones were sternly business-like as he
said—
“Then, madame, I must beg of you to disguise yourself as an
Englishwoman. Put on a tailor-made gown and a small felt hat, if
you please, and a short straight veil à l’anglaise, covering only the
upper part of the face. It would make it less easy for you to be
recognised if the dress was not black, but of some coloured cloth.
Bring also a fur cloak, for you will find it very cold. Which of the
ladies is to be summoned to attend you?”
“Pardon me, madame; that is my place,” said Baroness von
Hilfenstein, as the Queen looked round helplessly.
“I cannot consent to that, Baroness,” said Cyril. “You could not
support the fatigues of the journey, and moreover, your presence will
be needed here. Have you any preference as to your attendant,
madame?”
“I should like to have Fräulein von Staubach if—if you—if it
would not do any harm,” faltered the Queen.
“That is the very selection I would have ventured to suggest,
madame. Fräulein von Staubach speaks Thracian well, and although
the passport is made out for a German, we may find it desirable to
change our disguise after a time. May I beg of you, Fräulein, to
dress yourself to play the part of a nurse, and to see that the King is
warmly wrapped up? Will you also pack a small bag with necessaries
for her Majesty, and another for yourself. They must not be too large
to be carried conveniently in the hand, for we have to cross the park
on foot before we can reach the vehicle which is awaiting us. And
pray waste no time. Every minute is precious.”
The three ladies disappeared promptly, and Cyril stood waiting
for what seemed to him to be hours. He curbed his impatience, and
whiled away the time by making one or two final arrangements with
M. Stefanovics; but they had both relapsed into an uneasy silence
before Baroness von Hilfenstein entered the room, and beckoned
Cyril out of earshot of the chamberlain.
“You think success is possible in this enterprise of yours,
Count?”
“Certainly possible, Baroness; and possibly certain.”
“I did not come to ask you to play upon words,” very severely.
“I ask your pardon, Baroness. The danger has excited me. I
think I must be fey.”
“I do not know that word, my dear Count.”
“It only means that some one is walking over my grave,
Baroness.”
“Do not speak in that way,” said the old lady, looking at him with
alarm not unmixed with tenderness. “Count, I cannot forget to-night
that you are a young man, although it has never struck me before.
Can I depend upon you to take such care of the Queen as I myself
should take were I with you?”
“I promise you, Baroness, that I will take as much care of the
Queen as she will allow me.”
“She will prove somewhat trying, I do not doubt. But you have
mastered her to-night, and that may change her manner towards
you. I cannot tell—I am afraid——”
“Are you afraid of her Majesty or of me, Baroness?”
The sudden question recalled the Baroness to her duty. “I am
not afraid of either of you; but I am very much afraid of
circumstances,” she replied, looking straight at Cyril.
“I have always aimed at moulding circumstances, Baroness, and
not at allowing them to mould me.”
“That is very well, but circumstances are sometimes too strong
—— But guard well the proprieties, my dear Count. Maintain the
niceties of etiquette with even unusual care, for they will form a
barrier to protect the Queen from her unfortunate surroundings. You
will promise me this?”
“Anything in reason, Baroness. I will do my best, certainly. But,”
changing the subject with some impatience, “may I remind you that
our escape will largely depend upon you? Of course it is impossible
to defend this house; but the longer you can keep the conspirators
in talk before they discover the Queen’s absence, the better for us.”
“You are right. I will meet them and argue with them, refuse to
allow them to proceed, and retreat only inch by inch before threats
of violence. And then, Count, I will try another expedient. When they
insist on seeing the Queen, my daughter shall personate her
Majesty. They are about the same height, and through the crape veil
it will be impossible to detect the difference.”
“It is an excellent idea, Baroness, if Baroness Paula has the
nerve to carry it out. But what about the King?”
“We will dress up a pillow in his clothes, and Mrs Jones shall
carry it. If we are hurried away to the Bishop’s palace at once, they
will not detect the trick until the morning, which will—— Oh, is that
you, Mrs Jones?”
“Yes, ma’am, it is; and hearin’ no good of myself, as they say no
eavesdroppers don’t. I think I see myself carryin’ about a pillow
dressed up in his Majesty’s clothes, and the precious lamb himself
left to that there Frawline!”
“Mrs Jones, we cannot take you with us.” Cyril spoke sharply,
noting that Mrs Jones was ready equipped for the journey. “You
would be recognised anywhere,” for tales of the magnificence of
demeanour of the King’s nurse, and her unbending deportment
towards the natives of her land of exile, circulated wherever the
Court moved, “and that would ruin the whole scheme. You must stay
here, and obey the orders of the Baroness, and so help us to save
the King.”
“Thank you, my lord; and what if I declines to stay here?”
“Then you will have the responsibility of destroying the King’s
only chance of escape. We are in your hands, Mrs Jones. If you will
stay behind, it will help to gain time for us to get beyond the reach
of pursuit; but you may as well go and inform the conspirators at
once that we are trying to escape as insist on coming with us. Which
is it to be?”
“My lord, if me stayin’ here can help the King and your lordship
to escape, I’ll stay here till Doomsday, and no one shan’t drag me
from the house, not if wild horses was to try it. I thank you, my lord,
for talkin’ to me like a reasonable Christian woman, and here I stays,
and no thanks to no one else, neither!”
And Mrs Jones retired with added dignity, just as the Queen
entered the room, looking absurdly young and girlish in her grey
tweed dress and simple hat, and followed by Fräulein von Staubach,
with the little King, well wrapped up, fast asleep in her arms.
“One moment before we start, madame,” said Cyril. “From this
time forward you are an English lady, Mrs Weston, and I am your
brother, Arthur Cleeves. Your Christian name is Lilian. The King is
your son Tommy, Fräulein von Staubach is his German nurse Julie,
and my clerk Paschics, who is waiting for us on the other side of the
park, is Carlo, an Italian courier. We are travelling by road, and our
carriage has broken down, which makes it necessary for us to hire a
country cart to convey us to the next posting-station. Let me
impress upon you the necessity of speaking nothing but English, and
of keeping to our assumed names, even when no strangers are
present, for the sake of practice. I think you had better give me the
child, Fr—Julie, and I will take my sister’s bag, if you can manage
your own. Now we had better start—Lilian.”
The Queen gave Baroness von Hilfenstein a half-tearful, half-
smiling glance, for the old lady’s face was a study when she heard
Cyril’s words, and it was with difficulty that she restrained herself
from insisting, even at this late hour, on the abandonment of the
scheme. “Take care of her Majesty,” she whispered anxiously to
Fräulein von Staubach, holding her back from descending the stairs
after the other two; “remind her constantly of her position. Maintain
all the restraints possible, and remember that if anything happens, I
shall never forgive you or myself.”
Very much flurried, and totally unable to comprehend the full
force of the warning, Fräulein von Staubach nevertheless promised
faithfully to observe it, and hurried down the steps after her
mistress, who had reached the door at the foot of the staircase.
Here the fugitives stood for a moment in the shadow, listening to the
beating of their own hearts, while M. Stefanovics, emerging from the
doorway, joined the sentry in his walk, and accompanied him to the
end of the terrace, where he directed his attention to an imaginary
glare in the sky over the city, which he suggested was due to a
street-fire. While the sentry, deeply interested (for he knew
something of the plot, and was watching for any sign of its being
carried out), was doing his best to see the remarkably faint and fitful
glow pointed out to him, Cyril directed the Queen and Fräulein von
Staubach to cross the terrace as quietly as possible, and conceal
themselves among the shrubs on the farther side. The next moment
he followed them; but the interval had been long enough to allow a
fear to seize him which covered his brow with cold sweat. What if
the conspirators were already in hiding among those very bushes?
But no one appeared, and no movement was made, and he led the
way through the gardens, walking on the grass wherever he could
so as to avoid making any sound, and then through a wicket-gate
into the park. Here their progress was much more satisfactory, for
they were quite out of sight from the house, and could walk rapidly
over the turf, although it required some care to avoid coming into
unpleasantly close and sudden contact with the trees. But when the
more open ground was left behind, and it was necessary to plunge
into a thick wood, the ladies found their difficulties greatly increased,
and the more so that Cyril, encumbered as he was with the sleeping
child and the Queen’s bag, could do little to aid them. They made no
complaint, and toiled on bravely through briers and wet bushes,
which had a perverse way of springing back and striking the unwary
traveller on the face; but it was no small relief to Cyril when they
reached the boundary of the estate, and a whistle from him brought
up Paschics to relieve him temporarily of the burden of the little
King, and to help the ladies over the fence. They descended the
steep bank to the road, where the Queen stopped suddenly, aghast
at the sight of the vehicle awaiting them, and then laughed until the
tears came into her eyes. It was the usual light wooden cart of the
more advanced among the farmers, without springs or tilt, and
provided with a board by way of driving-seat. The floor was covered
thickly with straw, and there were several rugs stowed away in the
front, while the two rough, stout little horses had had their bells
carefully removed.
“Come, Lilian, let me help you up,” said Cyril briskly, handing the
little King to Fräulein von Staubach, and mounting into the cart. “I
can make you and Tommy a most comfortable nest in the straw, and
there is a rug for Julie as well. Give me your hand, and Carlo will
show you where to put your foot.”
The Queen, with the tears still in her eyes, allowed herself to be
helped in, and sat silent as Cyril lifted the child and laid him in her
arms; but when Fräulein von Staubach had been established beside
her, and Paschics had produced a piece of tarpaulin, which he
fastened to the sides of the cart so as to shelter the inmates, she
put out her hand suddenly and laid it on Cyril’s.
“Don’t think I am ungrateful,” she said; “it is all so strange. I
feel as if I were in a dream. But I will do all I can to avoid being a
trouble to you.”
CHAPTER XI.
WAYFARING.

When in after-days Cyril looked back to the events of that night, they
seemed to him like the course of a bad dream. The first part of the
journey was easy enough, for the road was good, and he occupied
the driving-seat with Paschics, exchanging a word with him
occasionally, and keeping him supplied with cigars, for the Queen
had entreated them to smoke. But when some ten English miles had
been covered without interruption, it became necessary to leave the
road for an old and almost disused cart-track, leading through rough
and hilly country. By this means the first three posting-stations on
the road would be missed altogether, a step which was imperative
unless the fugitives were simply to be traced from point to point
along their way; but time was so precious that Cyril would have
been inclined to try whether it was impossible to slip past them
unnoticed, if it had not been that the hill-track, though rough, was
far shorter than the post-road. There was no more easy driving now.
Cyril and Paschics spent the greater part of the night in walking up
and down interminable hills, sometimes dragging the horses on,
sometimes holding them back, and varying these occupations by
pushing at the cart behind, or lifting the wheels out of pits of mud.
The two women and the child were so completely tired out that they
were scarcely awakened even by the most tremendous jolts, and
descents which would have appeared impossible in daylight were
attempted confidently by the light of the lantern which Paschics
carried, and which was constantly in request for the purpose of
consulting the map or the compass. At length the worst and longest
hill, having been successfully passed, proved to be the last one, and
the two men and the worn-out horses stumbled painfully into the
highroad. Looking at one another, in the grey light of the March
morning, Cyril and Paschics became aware that they both presented
a very disreputable appearance, and the short interval which was
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!

ebookgate.com

You might also like