Top Banner

of 542

Java-Structures.pdf

Apr 14, 2018

Download

Documents

Edgar Bravo
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/30/2019 Java-Structures.pdf

    1/541

    Java Structures

    Data Structures in Java for the Principled Programmer

    The7 Edition

    (Software release 33)

    Duane A. Bailey

    Williams CollegeSeptember 2007

  • 7/30/2019 Java-Structures.pdf

    2/541

    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.

  • 7/30/2019 Java-Structures.pdf

    3/541

    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 Cant 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 . . . . . . . . . . . . . . . . . . . . . . . . . 503.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

  • 7/30/2019 Java-Structures.pdf

    4/541

    iv Contents

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

    4 Generics 694.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 A s s o c i a t i o n s . . . . . . . . . . . . . . . . . . . . 72

    4.2.2 Parameterizing the V e c t o r 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 . . . . . . . . . . . . . . . 915.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 . . . . . . . . . . . . . . . . . . . . 1497.1.1 Design of the Interface . . . . . . . . . . . . . . . . . . . . 150

    7.1.2 Development of an Abstract Implementation . . . . . . . . 1 5 1

    7.1.3 Implementation . . . . . . . . . . . . . . . . . . . . . . . . 152

    7.2 Example: Development of Generators . . . . . . . . . . . . . . . . 152

    7.3 Example: Playing Cards . . . . . . . . . . . . . . . . . . . . . . . 155

  • 7/30/2019 Java-Structures.pdf

    5/541

    Contents v

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

    8 Iterators 1618.1 Javas 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 . . . . . . . . . . . . . . . . 1889.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 . . . . . . . . . . . . . . . . . . . . 25311.1.1 Example: Comparable Ratios . . . . . . . . . . . . . . . . 2 5 4

    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

  • 7/30/2019 Java-Structures.pdf

    6/541

    vi Contents

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

    11.2.4 A Comparator-based Approach . . . . . . . . . . . . . . . 265

    11.2.5 The Ordered List . . . . . . . . . . . . . . . . . . . . . . . 26711.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 Gardners 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 . . . . . . . . . . . . . . . . . . . . . . . . . . 34514.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

  • 7/30/2019 Java-Structures.pdf

    7/541

    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 . . . . . . . . . . . . . . . . . . . . . . 42416.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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491B.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

  • 7/30/2019 Java-Structures.pdf

    8/541

    viii Contents

    B.3.3 The PrintStream Class . . . . . . . . . . . . . . . . . . . . 496B.3.4 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497

    B.4 Control Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . 498B.4.1 Conditional Statements . . . . . . . . . . . . . . . . . . . 498

    B.4.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499B.5 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502B.6 Inheritance and Subtyping . . . . . . . . . . . . . . . . . . . . . . 502

    B.6.1 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . 502B.6.2 Subtyping . . . . . . . . . . . . . . . . . . . . . . . . . . . 503B.6.3 Interfaces and Abstract Classes . . . . . . . . . . . . . . . 504

    B.7 Use of the Assert Command . . . . . . . . . . . . . . . . . . . . . 506B.8 Use of the Keyword P r o t e c t e d . . . . . . . . . . . . . . . . . . . 507

    C Collections 511C.1 Collection Class Features . . . . . . . . . . . . . . . . . . . . . . . 511

    C.2 Parallel Features . . . . . . . . . . . . . . . . . . . . . . . . . . . 511C.3 Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512

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

    Index 517

  • 7/30/2019 Java-Structures.pdf

    9/541

    for Mary,my wife and best friend

    withoutthe 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!

  • 7/30/2019 Java-Structures.pdf

    10/541

  • 7/30/2019 Java-Structures.pdf

    11/541

    Preface to the First Edition

    I T S A WONDERFUL TIME TO BE ALIVE. At least thats what Ive found myselfsaying 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. Thechallenge was to make these behemoths solve complex problems quickly.

    Today, computers are everywhere. They are in the office and at home. Theyspeak to us on telephones; they zap our food in the microwave. They makestarting cars in New England a possibility. Everyones using them. What hasaided their introduction into society is their diminished size and cost, and in-

    creased capability. The challenge is to make these behemoths solve complexproblems quickly.

    Thus, while the computer and its applications have changed over time, thechallenge remains the same: How can we get the best performance out of thecurrent 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 threedecades 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. Thefocus of this material is the identification and development of relativelyabstractprinciples for structuring data in ways that make programs efficient in terms oftheir 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 hasbeen met with increasing expectation. This text uses The Java ProgrammingLanguage1Javato structure data. Java is a new and exciting languagethat has received considerable public attention. At the time of this writing, forexample, Java is one of the few tools that can effectively use the Internet as acomputing resource. That particular aspect of Java is not touched on greatlyin this text. Still, Internet-driven applications in Java will need supporting datastructures. This book attempts to provide a fresh and focused approach to the

    design and implementation of classic structures in a manner that meshes wellwith existing Java packages. It is hoped that learning this material in Javawill improve the way working programmers craft programs, and the way futuredesigners craft languages.

    Pedagogical Implications. This text was developed specifically for use withCS2 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.

  • 7/30/2019 Java-Structures.pdf

    12/541

    xii Preface to the First Edition

    becomes not a brief encounter with object-oriented data structure design, but atouchstone for ones 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 newto Java, a couple of weeks early in the semester will be necessary with a goodcompanion text to introduce the student to new concepts, and an introductoryJava language text or reference manual is recommended. For students that needa quick introduction to Java we provide a tutorial in Appendix B. While the text

    N

    NW

    SWSE

    NE

    W

    S

    E

    was designed as a whole, some may wish to eliminate less important topicsand expand upon others. Students may wish to drop (or consider!) the sec-tion on induction (Section 5.2.2). The more nontraditional topicsincluding,for example, iteration and the notions of symmetry and frictionhave been in-cluded because I believe they arm programmers with important mechanisms for

    implementing and analyzing problems. In many departments the subtleties ofmore advanced structuresmaps (Chapter 15) and graphs (Chapter 16)maybe considered in an algorithms course. Chapter 6, a discussion of sorting, pro-vides very important motivating examples and also begins an early investigationof 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 freelyavailable over the Internet for noncommercial purposes. I encourage students,

    L i s t

    educators, and budding software engineers to download it, tear it down, build itup, 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 extensivedocumentation gleaned from the code by j a v a d o c . All documentationwithinthe book and on the Webincludes pre- and postconditions. The motivation for

    this style of commenting is provided in Chapter 2. While its hard to be militantabout commenting, this style of documentation provides an obvious, structuredapproach to minimally documenting ones methods that students can appreciateand users will welcome. These resources, as well as many others, are availablefrom McGraw-Hill at h t t p : / / w w w . m h h e . c o m / j a v a s t r u c t u r e s .

    Three icons appear throughout the text, as they do in the margin. The

    n i m

    top compass icon highlights the statement of a principlea statement that

    encourages abstract discussion. The middle icon marks the first appearance ofa particular class from the s t r u c t u r e package. Students will find these files atMcGraw-Hill, or locally, if theyve been downloaded. The bottom icon similarlymarks the appearance of example code.

    Finally, Id like to note an unfortunate movement away from studying theimplementation of data structures, in favor of studying applications. In the

    extreme this is a disappointing and, perhaps, dangerous precedent. The designof a data structure is like the solution to a riddle: the process of developing theanswer is as important as the answer itself. The text may, however, be used as areference for using the s t r u c t u r e package in other applications by selectively

    avoiding the discussions of implementation.

  • 7/30/2019 Java-Structures.pdf

    13/541

    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 consistedof 504 classes in 23 packages3 In Java 1.2 (also called Java 2) Sun rolled out1520 classes in 59 packages. This book is ready for Java 1.4, where the numberof 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 arestill 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. Thedevelopers at Sun have one purpose in mind: to make Java the indispensablelanguage of the current generation. As a result, documenting their progress on

    the development of data structures gives us valuable insight into the process ofdesigning useful data structures for general purpose programming. Those stu-dents and faculty considering a move to this second edition of Java Structureswill see first-hand some of the decisions that have been made in the interven-ing years. During that time, for example, the C o l l e c t i o n -based classes wereintroduced, and are generally considered an improvement. Another forceone similar to calcificationhas left a trail of backwards compatible featuresthat are sometimes difficult to understand. For example, the I t e r a t o r classwas introduced, but the E n u m e r a t i o n class was not deprecated. One subject ofthe first editionthe notion of C o m p a r a b l e classeshas been introduced into

    a number of important classes including S t r i n g and I n t e g e r . This is a stepforward and a reconsideration of what we have learned about that material haslead 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 ofJava where it blurs the view. For example, Java 2 introduces a L i s t interface(we applaud) but the V e c t o r class has been extended to include methods thatare, essentially, motivated by linked lists (we wonder). As this text points outfrequently, the purpose of an interface is often to provide reduced functionality.

    If the data structure does not naturallyprovide the functionality required by theapplication, it is probably not an effective tool for solving the problem: searchelsewhere 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, OReilly & Associates.

  • 7/30/2019 Java-Structures.pdf

    14/541

    xiv Preface to the Second Edition

    As of this writing, more than 100, 000 individuals have searched for anddownloaded the s t r u c t u r e package. To facilitate using the comprehensive set

    of classes with the Java 2 environment, we have provided a number of featuresthat support the use of the s t r u c t u r e 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 toshape this edition of Java Structures. Parth Doshi and Alex GlendaydiligentWilliams studentspointed out a large number of typos and stretches of logic.Kim Bruce, Andrea Danyluk, Jay Sachs, and Jim Teresco have taught this courseat Williams over the past few years, and have provided useful feedback. I tipmy hat to Bill Lenhart, a good friend and advisor, who has helped improve thistext 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 (NorthCarolina State University), Yannick Daoudi (McGill University), Walter Daugh-erty (Texas A&M University), Subodh Kumar (Johns Hopkins University), ToshimiMinoura (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), CynthiaBrown 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-HillKelly Lowery, Melinda Dougharty, John

    Wannemacher, and Joyce Berendeshave attempted the impossible: to keep mewithin a deadline. David Hash, Phil Meek, and Jodi Banowetz are responsiblefor the look and feel of things. I am especially indebted to Lucy Mullins, JudyGantenbein, 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, mybest work will be recognized in my children, Kate, Megan, and Ryan. Noneof these projects, of course, would be possible without the support of my bestfriend, my north star, and my partner, Mary.

    Enjoy!

    Duane A. BaileyWilliamstown, May 2002

  • 7/30/2019 Java-Structures.pdf

    15/541

    Preface to the 7 EditionIn your hand is a special edition of Java Structures designed for use with two

    semesters of Williams course on data structures, Computer Science 136. Thisversion is only marginally different than the preceding edition, but is positionedto 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 thecode available in this book will run on older JDKs. The one feature that wouldnot be available is Javas new S c a n n e r class from the j a v a . u t i l package; analternative is myR e a d S t r e a m class, which is lightly documented in Section B.3.1on page 494. It is a feature of the s t r u c t u r e package soon to be removed.

    In making this book available in this paperbound format, my hope is thatyou find it a more inviting place to write notes: additions, subtractions, andupdates that youre likely to have discussed in class. Sometimes youll identifyimprovements, and I hope youll pass those along to me. In any case, you candownload 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 s t r u c t u r e package can make use of generictypes.

    I have spent a considerable amount of time designing the s t r u c t u r e pack-age. The first structures were available 8 years ago when Java was still in itsinfancy. Many of the structures have since been incorporated (directly or indi-

    rectly) into Suns own J D K . (Yes, weve sold a few books in California.) Still, Ifeel the merit of my approach is a slimness that, in the end, you will not findsurprising.

    Meanwhile, for those of you keeping track, the following table (adaptedfrom the 121 cubic inch, 3 pound 6 ounce, Fifth edition of David Flanagansessential Java in a Nutshell) demonstrates the growth of Javas 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 a s s e r t

    1.5 (Java 5) 166 3562 Generics, autoboxing, and varargs.

    Seeing this reminds me of the comment made by Niklaus Wirth, designer ofPascal 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.

  • 7/30/2019 Java-Structures.pdf

    16/541

    xvi Preface to the

    7 Edition

    Acknowledgments. This book was primarily written for students of WilliamsCollege. The process of publishing and reviewing a text tends to move the focus

    off campus and toward the bottom line. The Route 7 edition4somewherebetween editions 2 and 3is 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, Im especially indebted to KatieCreel 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. BrentHeeringa 99 (Morris, now at Williams) showers all around him with youthfulenthusiasm.

    And a most special thanks to Bill Mueller for the shot heard around the

    worldthe game-winning run that showed all things were possible. Called byJoe Castiglione 68 (Colgate, now at Fenway):

    Three-and-one to Mueller. One out, nineth inning. 10-9 Yankees,runner at first. Heres the pitch...swing and a High Drive Deep toRight...Back Goes Sheffield to the Bullpen...AND IT IS GONE!...ANDTHE RED SOX HAVE WON IT!...ON A WALKOFF TWO RUN HOMERBY 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 itpasses through Williamstown and Middlebury.

  • 7/30/2019 Java-Structures.pdf

    17/541

    Chapter 0

    Introduction

    Concepts: Approaches to this material Principles

    This is an important notice.

    Please have it translated.

    The Phone Company

    YOUR MOTHER probably provided you with constructive toys, like blocks orTinkertoys1 or Lego bricks. These toys are educational: they teach us to thinkspatially and to build increasingly complex structures. You develop modulesthat 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 buildingstructures apply to writing programs, save one thing: there is, seemingly, nolimit 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 yourrunning 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 yourprogram. Choosing the wrong structures can cause your program to run poorlyor 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 theirvarious merits. This book focuses on the creation and analysis of traditionaldata structures in a modern programming environment, The Java ProgrammingLanguage, 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 availableto 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 h t t p : / / w w w . c s . w i l l i a m s . e d u / J a v a S t r u c t u r e s .

  • 7/30/2019 Java-Structures.pdf

    18/541

    2 Introduction

    trade. Some are mathematical and others are philosophical, but all considerthe process of programming well.

    The topics we cover are not all-inclusive. Some useful structures have beenleft 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 theend of each section. All are important for you to consider. For some problemsI 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 toride a unicycle, but if you never practiced, you would never learn. If you studyUnicycles: the

    ultimate riding

    structure.and understand these problems, you will find your design and analytical skillsare improved. As for your mother, shell 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 formalproblems in the back of the chapter, where theydo have answers)they shouldbe thought about carefully as you are reading along. You may find it useful tohave a pencil and paper handy to help you think about these problems on thefly.

    Exercise 0.1 Call3 your Mom and tell her youre completing your first exercise. Ifyou dont have a phone handy, drop her a postcard. Ask her to verify that shesproud 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, youmight find it useful to read through the source code online. As we first consider

    S t r u c t u r e

    the text of files online, the file name will appear in the margin, as you see here.The top icon refers to files in the s t r u c t u r e package, while the bottom iconrefers to files supporting examples.

    E x a m p l e

    One more pointthis book, like most projects, is an ongoing effort, andthe latest thoughts are unlikely to have made it to the printed page. If youare in doubt, turn to the website for the latest comments. You will also findonline documentation for each of the structures, generated from the code usingj a v a d o c . 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 notformally presented within this text.

    0.2 He Cant Say That, Can He?

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

    3 Dont e-mail her. Call her. Computers arent everything, and theyre a poor medium for a motherspride.

  • 7/30/2019 Java-Structures.pdf

    19/541

    0.2 He Cant Say That, Can He? 3

    to improve your skills as a programmer and a computer scientist, I invite youto read on. Sometimes these comments are so important that they appear as

    principles:

    Principle 1 The principled programmer understands a principle well enough to

    N

    NW

    SWSE

    NE

    W

    S

    E

    form an opinion about it.

    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 advicewould you give a new programmer?

    0.3 Surf to the website associated with this text and review the resourcesavailable to you.

    0.4 Which of the following structures are described in this text (see Append-ix D): B i n a r y S e a r c h T r e e , B i n a r y T r e e , B i t S e t , M a p , H a s h t a b l e , L i s t ?

    0.5 Surf to h t t p : / / w w w . j a v a s o f t . c o m and review the Java resources avail-able from Sun, the developers of Java.

    0.6 Review documentation for Suns j a v a . u t i l package. (See the CoreAPI Documentation at h t t p : / / w w w . j a v a s o f t . c o m .) Which of the followingdata structures are available in this package: B i n a r y S e a r c h T r e e , B i n a r y T r e e ,B i t S e t , D i c t i o n a r y , H a s h t a b l e , L i s t ?

    0.7 Check your local library or bookstore for Java reference texts.

    0.8 If you havent 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 s t r u c t u r e package. If none is tobe found, remember that the same documentation is available over the Internetfrom h t t p : / / w w w . c s . w i l l i a m s . e d u / J a v a S t r u c t u r e s .

    0.10 Find the examples electronically distributed with the s t r u c t u r e pack-age. Many of these examples are discussed later in this text.

  • 7/30/2019 Java-Structures.pdf

    20/541

  • 7/30/2019 Java-Structures.pdf

    21/541

    Chapter 1

    The Object-Oriented Method

    Concepts: Data structures Abstract data types

    Objects Classes Interfaces

    I will pick up the hook.

    You will see something new.

    Two things. And I call them

    Thing One and Thing Two.

    These Things will not bite you.They want to have fun.

    Theodor Seuss Geisel

    COMPUTER 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 methodto 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 providethe power to accurately and efficiently describe the details of large programsand 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:

    Object-oriented

    programming.oping templates for structures called classes. The templates are then used toconstruct instances or objects. A majority of the statements in object-oriented

    programs involve sending messages to objects to have them report or changetheir 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 toolfor writing working programs. In programming languages including Pascal,Scheme, and C, the details of a programs implementation are hidden away in

    its procedures or functions. This approach involves procedural abstraction. Inobject-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 thedesign of formal interfaces for objects in this chapter.

  • 7/30/2019 Java-Structures.pdf

    22/541

    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 arecircular, breadlike, and sweet. The particular ingredients in a donut are of littleconcern to you. Of course, Morningside is free to switch from one sweetener toanother, as long as the taste is preserved.1 The donuts ingredients list and itsconstruction 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 familiarwith the workings or semantics of strings or arrays, but, if pressed, we mightfind it difficult to describe their mechanics: Do all consecutive locations in thearray 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 orthe string behaves like a string we are happy. The less one knows about howarrays or strings are implemented, the less one becomes dependent on a partic-

    ular implementation. Another way to think about this abstractly is that the dataMacintosh andUNIX store

    strings

    differently.

    structure lives up to an implicit contract: a string is an ordered list of charac-ters, or elements of an array may be accessed in any order. The implementor ofthe data structure is free to construct it in any reasonable way, as long as all theterms of the contract are met. Since different implementors are in the habit ofmaking very different implementation decisions, anything that helps to hide theimplementation detailsany means of using abstractionserves to make theworld a better place to program.

    When used correctly, object-oriented programming allows the programmerto separate the details that are important to the user from the details that areonly 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 studystructures 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 eventhough we havent yet discussed how these structures might be implemented.Those abstract details that are important to the user of the structureincludingabstract semantics of the methodsmake up its contract or interface. The in-terface describes the abstract behavior of the structure. Most of us would agreethat 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 withan array; you can print a string directly, while printing an array involves explic-itly printing each of its elements. These distinctions suggest they have distinctabstract behaviors; there are distinctions in the design of their interfaces.

    The unimportant details hidden from the user are part of what makes upthe 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 changesthe flavor of the donut for the better. Some of the best apple cider donuts can be found at Atkinsapple farm in Amherst, Massachusetts.

  • 7/30/2019 Java-Structures.pdf

    23/541

    1.2 The Object Model 7

    Data

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 n

    0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 n

    L I C K E T Y S P L I T !E

    OS

    L I C K E T Y S P L I T !

    13

    Counted string

    Terminated string

    Data

    Count

    0

    Figure 1.1 Two methods of implementing a string. A counted string explicitly records

    its length. The terminated strings 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 stringwith 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 firstimplementation (called a counted string) has its length stored explicitly, whilethe 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 tosearch for the end-of-string mark. On the other hand, the size of a terminatedstring is limited only by the amount of available memory, while the longestcounted 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 canhide these details, users do not have to be distracted from their own important

    design work. As applications mature, a fixed interface to underlying objectsallows 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 withoutbothering the programmer. For example, if two strings have to be concatenatedinto 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 operationson themselves, the user doesnt have to worry about managing memory.

    1.2 The Object ModelTo 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 datathat determine its state. A point on a screen, for example, has two coordinates.

  • 7/30/2019 Java-Structures.pdf

    24/541

    8 The Object-Oriented Method

    A medical record maintains a name, a list of dependents, a medical history, anda 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 programmanipulates the data within its objects only through messages or method callsto the objects. A string might receive a message tell me your length, whilea medical record might receive a change insurance message. The string mes-sage simply accesses information, while the medical record method may involvechanging several pieces of information in this and other objects in a consistentmanner. If we directly modify the reference to the insurance company, we mayforget to modify similar references in each of the dependents. For large applica-tions with complex data structures, it can be extremely difficult to remember tocoordinate all the operations that are necessary to move a single complex objectfrom one consistent state to another. We opt, instead, to have the designer ofthe 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 mightuse the objects we create. These objects typically represent data structures, ourprimary interest. Occasionally we will develop control structuresstructureswhose 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

    objectan instance of a class. Like a record in other languages, an object has

    fields. Unlike records, objects also contain methods. Fields and methods of anobject may be declared p u b l i c , which means that they are visible to entitiesoutside the class, or p r o t e c t e d , in which case they may only be accessed bycode within methods of the class.2 A typical class declaration is demonstratedby the following simple class that keeps track of the ratio of two integer values:

    R a t i o

    p u b l i c c l a s s R a t i o

    {

    p r o t e c t e d i n t n u m e r a t o r ; / / n u m e r a t o r o f r a t i o

    p r o t e c t e d i n t d e n o m i n a t o r ; / / d e n o m i n a t o r o f r a t i o

    p u b l i c R a t i o ( i n t t o p , i n t b o t t o m )

    / / p r e : b o t t o m ! = 0

    / / p o s t : c o n s t r u c t s a r a t i o e q u i v a l e n t t o t o p : : b o t t o m

    {

    n u m e r a t o r = t o p ;

    d e n o m i n a t o r = b o t t o m ;

    r e d u c e ( ) ;

    2 This is not quite the truth. For a discussion of the facts, see Appendix B.8.

  • 7/30/2019 Java-Structures.pdf

    25/541

    1.3 Object-Oriented Terminology 9

    }

    p u b l i c i n t g e t N u m e r a t o r ( )

    / / p o s t : r e t u r n t h e n u m e r a t o r o f t h e f r a c t i o n

    {

    r e t u r n n u m e r a t o r ;

    }

    p u b l i c i n t g e t D e n o m i n a t o r ( )

    / / p o s t : r e t u r n t h e d e n o m i n a t o r o f t h e f r a c t i o n

    {

    r e t u r n d e n o m i n a t o r ;

    }

    p u b l i c d o u b l e g e t V a l u e ( )

    / / p o s t : r e t u r n t h e d o u b l e e q u i v a l e n t o f t h e r a t i o

    {

    r e t u r n ( d o u b l e ) n u m e r a t o r / ( d o u b l e ) d e n o m i n a t o r ;

    }

    p u b l i c R a t i o a d d ( R a t i o o t h e r )

    / / p r e : o t h e r i s n o n n u l l

    / / p o s t : r e t u r n n e w f r a c t i o n - - t h e s u m o f t h i s a n d o t h e r

    {

    r e t u r n n e w R a t i o ( t h i s . n u m e r a t o r * o t h e r . d e n o m i n a t o r +

    t h i s . d e n o m i n a t o r * o t h e r . n u m e r a t o r ,

    t h i s . d e n o m i n a t o r * o t h e r . d e n o m i n a t o r ) ;

    }

    p r o t e c t e d v o i d r e d u c e ( )

    / / p o s t : n u m e r a t o r a n d d e n o m i n a t o r a r e s e t s o t h a t

    / / t h e g r e a t e s t c o m m o n d i v i s o r o f t h e n u m e r a t o r a n d d e n o m i n a t o r i s 1

    {

    i n t d i v i s o r = g c d ( n u m e r a t o r , d e n o m i n a t o r ) ;

    i f ( d e n o m i n a t o r < 0 ) d i v i s o r = - d i v i s o r ;

    n u m e r a t o r / = d i v i s o r ;

    d e n o m i n a t o r / = d i v i s o r ;

    }

    p r o t e c t e d s t a t i c i n t g c d ( i n t a , i n t b )

    / / p o s t : c o m p u t e s t h e g r e a t e s t i n t e g e r v a l u e t h a t d i v i d e s a a n d b

    {

    i f ( a < 0 ) r e t u r n g c d ( - a , b ) ;

    i f ( a = = 0 ) {

    i f ( b = = 0 ) r e t u r n 1 ;

    e l s e r e t u r n b ;

    }

    i f ( b < a ) r e t u r n g c d ( b , a ) ;

    r e t u r n g c d ( b % a , a ) ;

    }

  • 7/30/2019 Java-Structures.pdf

    26/541

    10 The Object-Oriented Method

    p u b l i c S t r i n g t o S t r i n g ( )

    / / p o s t : r e t u r n s a s t r i n g t h a t r e p r e s e n t s t h i s f r a c t i o n .

    {

    r e t u r n g e t N u m e r a t o r ( ) + " / " + g e t D e n o m i n a t o r ( ) ;

    }

    }

    First, a R a t i o object maintains the numerator and denominator as protectedi n t s that are not directly modifiable by the user. The R a t i o method is a con-

    structor: a method whose name is the same as that of the class. (The formalcomments at the top of methods are pre- and postconditions; we discuss thesein detail in Chapter 2.) The constructor is called whenever a new R a t i o object isformed. Constructors initialize all the fields of the associated object, placing theobject into a predictable and consistent initial state. We declare the construc-

    tors for a classp u b l i c

    . To construct a newR a t i o

    object, users will have to callthese methods. The v a l u e method returns a d o u b l e that represents the ratio,while the g e t N u m e r a t o r and g e t D e n o m i n a t o r methods fetch the current valuesof the numerator and denominator of the fraction. The a d d method is useful foradding one R a t i o to another; the result is a newly constructed R a t i o object.Finally, the t o S t r i n g method generates the preferred printable representationof the object; we have chosen to represent it in fractional form.

    Two methods, r e d u c e and g c d , are utility methods. The g c d method com-putes the greatest common divisor of two values using Euclids method, one ofthe oldest numerical algorithms used today. It is used by the r e d u c e method toreduce the numerator and denominator to lowest terms by removing any com-

    mon factors. Both are declared p r o t e c t e d because computing the reduction isnot a necessary (or obvious) operation to be performed on ratios of integers;

    its part of the implementation. Theg c d

    method is declareds t a t i c

    becausethe algorithm can be used at any timeits utility is independent of the numberof R a t i o objects that exist in our program. The r e d u c e method, on the otherhand, works only with a R a t i o object.

    Exercise 1.1 Nearly everything can be improved. Are there improvements thatmight be made to the g c d method? Can you write the method iteratively? Isiteration an improvement?

    As with the R a t i o class, data fields are usually declared p r o t e c t e d . To ma-nipulate protected fields the user must invoke p u b l i c methods. The followingexample demonstrates the manipulation of the R a t i o class:

    p u b l i c s t a t i c v o i d m a i n ( S t r i n g [ ] a r g s )

    {

    R a t i o r = n e w R a t i o ( 1 , 1 ) ; / / r = = 1 . 0

    r = n e w R a t i o ( 1 , 2 ) ; / / r = = 0 . 5

    r . a d d ( n e w R a t i o ( 1 , 3 ) ) ; / / s u m c o m p u t e d , b u t r s t i l l 0 . 5

    r = r . a d d ( n e w R a t i o ( 2 , 8 ) ) ; / / r = = 0 . 7 5

    S y s t e m . o u t . p r i n t l n ( r . g e t V a l u e ( ) ) ; / / 0 . 7 5 p r i n t e d

  • 7/30/2019 Java-Structures.pdf

    27/541

    1.4 A Special-Purpose Class: A Bank Account 11

    S y s t e m . o u t . p r i n t l n ( r . t o S t r i n g ( ) ) ; / / c a l l s t o S t r i n g ( )

    S y s t e m . o u t . p r i n t l n ( r ) ; / / c a l l s t o S t r i n g ( )

    }

    To understand the merit of this technique of class design, we might draw ananalogy 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 ofthe socket, are provided without giving any details about the implementationof the object. If light socket manufacturers depended on a particular imple-mentation of lightbulbsfor example the socket only supported bright xenonbulbsit might ultimately restrict the variety of suppliers of lightbulbs in thefuture. Likewise, manufacturers of lightbulbs should be able to have a cer-tain freedom in their implementation: as long as they only draw current in anagreed-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 incandescentor 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 implementsome set of structures with a common theme. The classes of this text, for ex-ample, are members of the s t r u c t u r e package. In the same way that there areusers of classes, there are users of packages, and much of the analogy holds. Inparticular, classes may be declared p u b l i c , in which case they may be used byanyone who imports the package into their program. If a class is not p u b l i c , itis automatically considered p r o t e c t e d . These p r o t e c t e d classes may only beconstructed 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 B a n k A c c o u n t .Many times, it is necessary to provide a tag associated with an instance of adata structure. You might imagine that your bank balance is kept in a databaseat your bank. When you get money for a trip through the Berkshires, you swipeyour card through an automated teller bringing up your account. Your account Automated

    teller: a robotic

    palm reader.number, presumably, is unique to your account. Nothing about you or yourbanking history is actually stored in your account number. Instead, that num-ber is used to find the record linked to your account: the bank searches for astructure associated with the number you provide. Thus a B a n k A c c o u n t is a sim-ple, but important, data structure. It has an a c c o u n t (an identifier that neverchanges) and a b a l a n c e (that potentially does change). The public methods of

    such a structure are as follows:

    B a n k A c c o u n t

    p u b l i c c l a s s B a n k A c c o u n t

    {

    p u b l i c B a n k A c c o u n t ( S t r i n g a c c , d o u b l e b a l )

    / / p r e : a c c o u n t i s a s t r i n g i d e n t i f y i n g t h e b a n k a c c o u n t

  • 7/30/2019 Java-Structures.pdf

    28/541

    12 The Object-Oriented Method

    / / b a l a n c e i s t h e s t a r t i n g b a l a n c e

    / / p o s t : c o n s t r u c t s a b a n k a c c o u n t w i t h d e s i r e d b a l a n c e

    p u b l i c b o o l e a n e q u a l s ( O b j e c t o t h e r )

    / / p r e : o t h e r i s a v a l i d b a n k a c c o u n t

    / / p o s t : r e t u r n s t r u e i f t h i s b a n k a c c o u n t i s t h e s a m e a s o t h e r

    p u b l i c S t r i n g g e t A c c o u n t ( )

    / / p o s t : r e t u r n s t h e b a n k a c c o u n t n u m b e r o f t h i s a c c o u n t

    p u b l i c d o u b l e g e t B a l a n c e ( )

    / / p o s t : r e t u r n s t h e b a l a n c e o f t h i s b a n k a c c o u n t

    p u b l i c v o i d d e p o s i t ( d o u b l e a m o u n t )

    / / p o s t : d e p o s i t m o n e y i n t h e b a n k a c c o u n t

    p u b l i c v o i d w i t h d r a w ( d o u b l e a m o u n t )

    / / p r e : t h e r e a r e s u f f i c i e n t f u n d s i n t h e a c c o u n t

    / / p o s t : w i t h d r a w m o n e y f r o m t h e b a n k a c c o u n t

    }

    The substance of these methods has purposefully been removed because, again,it is unimportant for us to know exactly how a B a n k A c c o u n t is implemented.We have ways to construct and compare B a n k A c c o u n t s, as well as ways to readthe account number or balance, or update the balance.

    Lets look at the implementation of these methods, individually. To build a

    new bank account, you must use the n e w operator to call the constructor withtwo parameters. The account number provided never changes over the life ofthe B a n k A c c o u n t if it were necessary to change the value of the account num-

    ber, a newB a n k A c c o u n t

    would have to be made, and the balance would have tobe transferred from one to the other. The constructor plays the important roleof performing the one-time initialization of the account number field. Here isthe code for a B a n k A c c o u n t constructor:

    p r o t e c t e d S t r i n g a c c o u n t ; / / t h e a c c o u n t n u m b e r

    p r o t e c t e d d o u b l e b a l a n c e ; / / t h e b a l a n c e a s s o c i a t e d w i t h a c c o u n t

    p u b l i c B a n k A c c o u n t ( S t r i n g a c c , d o u b l e b a l )

    / / p r e : a c c o u n t i s a s t r i n g i d e n t i f y i n g t h e b a n k a c c o u n t

    / / b a l a n c e i s t h e s t a r t i n g b a l a n c e

    / / p o s t : c o n s t r u c t s a b a n k a c c o u n t w i t h d e s i r e d b a l a n c e

    {

    a c c o u n t = a c c ;

    b a l a n c e = b a l ;

    }

    Two fields a c c o u n t and b a l a n c e of the B a n k A c c o u n t object are responsible

    for maintaining the objects state. The a c c o u n t keeps track of the account num-ber, while the b a l a n c e field maintains the balance.

  • 7/30/2019 Java-Structures.pdf

    29/541

    1.4 A Special-Purpose Class: A Bank Account 13

    Since account numbers are unique to B a n k A c c o u n t s, to check to see if twoaccounts are the same, we need only compare the a c c o u n t fields. Heres the

    code:

    p u b l i c b o o l e a n e q u a l s ( O b j e c t o t h e r )

    / / p r e : o t h e r i s a v a l i d b a n k a c c o u n t

    / / p o s t : r e t u r n s t r u e i f t h i s b a n k a c c o u n t i s t h e s a m e a s o t h e r

    {

    B a n k A c c o u n t t h a t = ( B a n k A c c o u n t ) o t h e r ;

    / / t w o a c c o u n t s a r e t h e s a m e i f a c c o u n t n u m b e r s a r e t h e s a m e

    r e t u r n t h i s . a c c o u n t . e q u a l s ( t h a t . a c c o u n t ) ;

    }

    Notice that the B a n k A c c o u n t e q u a l s method calls the e q u a l s method of the key,

    a S t r i n g . Both B a n k A c c o u n t and S t r i n g are nonprimitive types, or examplesof O b j e c t s. Every object in Java has an e q u a l s method. If you dont explicitly

    provide one, the system will write one for you. Generally speaking, one shouldassume that the automatically written or default e q u a l s method is of little use.This notion of equality of objects is often based on the complexities of ourabstraction; its design must be considered carefully.

    One can ask the B a n k A c c o u n t about various aspects of its state by calling itsg e t A c c o u n t or g e t B a l a n c e methods:

    p u b l i c S t r i n g g e t A c c o u n t ( )

    / / p o s t : r e t u r n s t h e b a n k a c c o u n t n u m b e r o f t h i s a c c o u n t

    {

    r e t u r n a c c o u n t ;

    }

    p u b l i c d o u b l e g e t B a l a n c e ( )

    / / p o s t : r e t u r n s t h e b a l a n c e o f t h i s b a n k a c c o u n t

    {

    r e t u r n b a l a n c e ;

    }

    These methods do little more than pass along the information found in thea c c o u n t and b a l a n c e fields, respectively. We call such methods accessors. In adifferent implementation of the B a n k A c c o u n t , the balance would not have to beexplicitly storedthe value might be, for example, the difference between twofields, d e p o s i t s and d r a f t s . Given the interface, it is not much of a concern tothe user which implementation is used.

    We provide two more methods, d e p o s i t and w i t h d r a w , that explicitly mod-ify the current balance. These are mutator methods:

    p u b l i c v o i d d e p o s i t ( d o u b l e a m o u n t )

    / / p o s t : d e p o s i t m o n e y i n t h e b a n k a c c o u n t

    {

    b a l a n c e = b a l a n c e + a m o u n t ;

    }

  • 7/30/2019 Java-Structures.pdf

    30/541

    14 The Object-Oriented Method

    p u b l i c v o i d w i t h d r a w ( d o u b l e a m o u n t )

    / / p r e : t h e r e a r e s u f f i c i e n t f u n d s i n t h e a c c o u n t

    / / p o s t : w i t h d r a w m o n e y f r o m t h e b a n k a c c o u n t

    {

    b a l a n c e = b a l a n c e - a m o u n t ;

    }

    Because we would like to change the balance of the account, it is important tohave a method that allows us to modify it. On the other hand, we purposefullydont have a s e t A c c o u n t 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 21

    2 percent interest for 20 years. It makes use of theB a n k A c c o u n t object just outlined:

    p u b l i c s t a t i c v o i d m a i n ( S t r i n g [ ] a r g s )

    {

    / / Q u e s t i o n : i s i t b e t t e r t o i n v e s t $ 1 0 0 o v e r 1 0 y e a r s a t 5 %

    / / o r t o i n v e s t $ 1 0 0 o v e r 2 0 y e a r s a t 2 . 5 % i n t e r e s t ?

    B a n k A c c o u n t j d = n e w B a n k A c c o u n t ( " J a i n D o u g h " , 1 0 0 . 0 0 ) ;

    B a n k A c c o u n t j s = n e w B a n k A c c o u n t ( " J o n S m y t h e " , 1 0 0 . 0 0 ) ;

    f o r ( i n t y e a r s = 0 ; y e a r s < 1 0 ; y e a r s + + )

    {

    j d . d e p o s i t ( j d . g e t B a l a n c e ( ) * 0 . 0 5 ) ;

    }

    f o r ( i n t y e a r s = 0 ; y e a r s < 2 0 ; y e a r s + + )

    {

    j s . d e p o s i t ( j s . g e t B a l a n c e ( ) * 0 . 0 2 5 ) ;

    }

    S y s t e m . o u t . p r i n t l n ( " J a i n i n v e s t s $ 1 0 0 o v e r 1 0 y e a r s a t 5 % . " ) ;

    S y s t e m . o u t . p r i n t l n ( " A f t e r 1 0 y e a r s " + j d . g e t A c c o u n t ( ) +

    " h a s $ " + j d . g e t B a l a n c e ( ) ) ;

    S y s t e m . o u t . p r i n t l n ( " J o n i n v e s t s $ 1 0 0 o v e r 2 0 y e a r s a t 2 . 5 % . " ) ;

    S y s t e m . o u t . p r i n t l n ( " A f t e r 2 0 y e a r s " + j s . g e t A c c o u n t ( ) +

    " h a s $ " + j s . g e t B a l a n c e ( ) ) ;

    }

    Exercise 1.2 Which method of investment would you pick?

    1.5 A General-Purpose Class: An Association

    The following small application implements a Pig Latin translator based on aAt least Dr.Seuss started

    with 50 words!dictionary of nine words. The code makes use of an array of A s s o c i a t i o n s,each of which establishes a relation between an English word and its Pig Latin

  • 7/30/2019 Java-Structures.pdf

    31/541

    1.5 A General-Purpose Class: An Association 15

    translation. For each string passed as the argument to the m a i n method, thedictionary is searched to determine the appropriate translation.

    a t i n l a y

    p u b l i c c l a s s a t i n L a y {

    / / a p i g l a t i n t r a n s l a t o r f o r n i n e w o r d s

    p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] )

    {

    / / b u i l d a n d f i l l o u t a n a r r a y o f n i n e t r a n s l a t i o n s

    A s s o c i a t i o n d i c t [ ] = n e w A s s o c i a t i o n [ 9 ] ;

    d i c t [ 0 ] = n e w A s s o c i a t i o n ( " a " , " a a y " ) ;

    d i c t [ 1 ] = n e w A s s o c i a t i o n ( " b a d " , " a d b a y " ) ;

    d i c t [ 2 ] = n e w A s s o c i a t i o n ( " h a d " , " a d h a y " ) ;

    d i c t [ 3 ] = n e w A s s o c i a t i o n ( " d a d " , " a d d a y " ) ;

    d i c t [ 4 ] = n e w A s s o c i a t i o n ( " d a y " , " a y d a y " ) ;

    d i c t [ 5 ] = n e w A s s o c i a t i o n ( " h o p " , " o p h a y " ) ;

    d i c t [ 6 ] = n e w A s s o c i a t i o n ( " o n " , " o n a y " ) ;

    d i c t [ 7 ] = n e w A s s o c i a t i o n ( " p o p " , " o p p a y " ) ;

    d i c t [ 8 ] = n e w A s s o c i a t i o n ( " s a d " , " a d s a y " ) ;

    f o r ( i n t a r g n = 0 ; a r g n < a r g s . l e n g t h ; a r g n + + )

    { / / f o r e a c h a r g u m e n t

    f o r ( i n t d i c t n = 0 ; d i c t n < d i c t . l e n g t h ; d i c t n + + )

    { / / c h e c k e a c h d i c t i o n a r y e n t r y

    i f ( d i c t [ d i c t n ] . g e t K e y ( ) . e q u a l s ( a r g s [ a r g n ] ) )

    S y s t e m . o u t . p r i n t l n ( d i c t [ d i c t n ] . g e t V a l u e ( ) ) ;

    }

    }

    }

    }

    When this application is run with the arguments h o p o n p o p , the results are

    o p h a y

    o n a y

    o p p a y

    While this application may seem rather trivial, it is easy to imagine a large-scaleapplication with similar needs.3

    We now consider the design of the A s s o c i a t i o n . Notice that while the typeof data maintained is different, the purpose of the A s s o c i a t i o n is very similarto that of the B a n k A c c o u n t class we discussed in Section 1.4. An A s s o c i a t i o n

    is a key-value pair such that the k e y cannot be modified. Here is the interfacefor the A s s o c i a t i o n class:

    A s s o c i a t i o n

    i m p o r t j a v a . u t i l . M a p ;

    3 Pig Latin has played an important role in undermining court-ordered restrictions placed on musicpiracy. When Napsterthe rebel music trading firmput in checks to recognize copyrighted musicby title, traders used Pig Latin translators to foil the recognition software!

  • 7/30/2019 Java-Structures.pdf

    32/541

    16 The Object-Oriented Method

    p u b l i c c l a s s A s s o c i a t i o n i m p l e m e n t s M a p . E n t r y

    {

    p u b l i c A s s o c i a t i o n ( O b j e c t k e y , O b j e c t v a l u e )

    / / p r e : k e y i s n o n - n u l l

    / / p o s t : c o n s t r u c t s a k e y - v a l u e p a i r

    p u b l i c A s s o c i a t i o n ( O b j e c t k e y )

    / / p r e : k e y i s n o n - n u l l

    / / p o s t : c o n s t r u c t s a k e y - v a l u e p a i r ; v a l u e i s n u l l

    p u b l i c b o o l e a n e q u a l s ( O b j e c t o t h e r )

    / / p r e : o t h e r i s n o n - n u l l A s s o c i a t i o n

    / / p o s t : r e t u r n s t r u e i f f t h e k e y s a r e e q u a l

    p u b l i c O b j e c t g e t V a l u e ( )

    / / p o s t : r e t u r n s v a l u e f r o m a s s o c i a t i o n

    p u b l i c O b j e c t g e t K e y ( )

    / / p o s t : r e t u r n s k e y f r o m a s s o c i a t i o n

    p u b l i c O b j e c t s e t V a l u e ( O b j e c t v a l u e )

    / / p o s t : s e t s a s s o c i a t i o n ' s v a l u e t o v a l u e

    }

    For the moment, we will ignore the references to M a p and M a p . e n t r y ; these willbe explained later, in Chapter 15. What distinguishes an A s s o c i a t i o n from amore specialized class, like B a n k A c c o u n t , is that the fields of an A s s o c i a t i o n are type O b j e c t . The use of the word O b j e c t in the definition of an A s s o c i a t i o n makes the definition very general: any value that is of type O b j e c t any non-primitive data type in Javacan be used for the k e y and v a l u e fields.

    Unlike the B a n k A c c o u n t class, this class has two different constructors:

    p r o t e c t e d O b j e c t t h e K e y ; / / t h e k e y o f t h e k e y - v a l u e p a i r

    p r o t e c t e d O b j e c t t h e V a l u e ; / / t h e v a l u e o f t h e k e y - v a l u e p a i r

    p u b l i c A s s o c i a t i o n ( O b j e c t k e y , O b j e c t v a l u e )

    / / p r e : k e y i s n o n - n u l l

    / / p o s t : c o n s t r u c t s a k e y - v a l u e p a i r

    {

    A s s e r t . p r e ( k e y ! = n u l l , " K e y m u s t n o t b e n u l l . " ) ;

    t h e K e y = k e y ;

    t h e V a l u e = v a l u e ;

    }

    p u b l i c A s s o c i a t i o n ( O b j e c t k e y )

    / / p r e : k e y i s n o n - n u l l

    / / p o s t : c o n s t r u c t s a k e y - v a l u e p a i r ; v a l u e i s n u l l

    {

    t h i s ( k e y , n u l l ) ;

    }

  • 7/30/2019 Java-Structures.pdf

    33/541

    1.5 A General-Purpose Class: An Association 17

    The first constructorthe constructor distinguished by having two parame-tersallows the user to construct a new A s s o c i a t i o n by initializing both fields.

    On occasion, however, we may wish to have an A s s o c i a t i o n whose k e y field isset, but whose v a l u e field is left referencing nothing. (An example might be a

    medical record: initially the medical history is incomplete, perhaps waiting tobe forwarded from a previous physician.) For this purpose, we provide a sin-gle parameter constructor that sets the v a l u e field to n u l l . Note that we uset h i s ( k e y , n u l l ) as the body. The one-parameter constructor calls this objectstwo-parameter constructor with n u l l as the second parameter. We write theconstructors in this dependent manner so that if the underlying implementationof the A s s o c i a t i o n had to be changed, only the two-parameter method wouldhave to be updated. It also reduces the complexity of the code and saves yourfingerprints!

    Now, given a particular A s s o c i a t i o n , it is useful to be able to retrieve thekey or value. Since the implementation is hidden, no one outside the class isable to see it. Users must depend on the accessor methods to observe the data.

    p u b l i c O b j e c t g e t V a l u e ( )

    / / p o s t : r e t u r n s v a l u e f r o m a s s o c i a t i o n

    {

    r e t u r n t h e V a l u e ;

    }

    p u b l i c O b j e c t g e t K e y ( )

    / / p o s t : r e t u r n s k e y f r o m a s s o c i a t i o n

    {

    r e t u r n t h e K e y ;

    }

    When necessary, the method s e t V a l u e can be used to change the value associ-ated with the key. Thus, the s e t V a l u e method simply takes its parameter andassigns it to the v a l u e field:

    p u b l i c O b j e c t s e t V a l u e ( O b j e c t v a l u e )

    / / p o s t : s e t s a s s o c i a t i o n ' s v a l u e t o v a l u e

    {

    O b j e c t o l d V a l u e = t h e V a l u e ;

    t h e V a l u e = v a l u e ;

    r e t u r n o l d V a l u e ;

    }

    There are other methods that are made available to users of the A s s o c i a t i o n

    class, but we will not discuss the details of that code until later. Some of themethods 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-rectly, so that we will not have to reimplement it in the future.

    Principle 2 Free the future: reuse code.

    N

    NW

    SWSE

    NE

    W

    S

    E

  • 7/30/2019 Java-Structures.pdf

    34/541

    18 The Object-Oriented Method

    It is difficult to fight the temptation to design data structures from scratch. Weshall 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 ofprevious work.

    1.6 Sketching an Example: A Word List

    Suppose were interested in building a game of Hangman. The computer selectsrandom words and we try to guess them. Over several games, the computershould pick a variety of words and, as each word is used, it should be removedfrom the word list. Using an object-oriented approach, well determine theessential features of a W o r d L i s t , the Java object that maintains our list of words.

    Our approach to designing the data structures has the following five informalsteps:

    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 yourobject. Information about an objects state is carried within the objectbetween operations that modify the state. Since there may be many ways

    to encode the state of your object, your description of the state may bevery general.

    3. Identify any rules of consistency. In the R a t i o class, for example, it wouldnot 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 aresynthetic: their sole responsibility is to get a new object into a good initial

    and consistent state. Dont forget to consider the best state for an objectconstructed using the parameterless default constructor.

    5. Identify the types and kinds of information that, though declared p r o - t e c t e d , can efficiently provide the information needed by the p u b l i c methods. Important choices about the internals of a data structure areusually made at this time. Sometimes, competing approaches are devel-oped until a comparative evaluation can be made. That is the subject ofmuch of this book.

    The operations necessary to support a list of words can be sketched outeasily, even if we dont know the intimate details of constructing the Hangmangame 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, wecan identify the following general use of the W o r d L i s t object:

  • 7/30/2019 Java-Structures.pdf

    35/541

    1.6 Sketching an Example: A Word List 19

    W o r d L i s t l i s t ; / / d e c l a r a t i o n

    S t r i n g t a r g e t W o r d ;

    l i s t = n e w W o r d L i s t ( 1 0 ) ; / / c o n s t r u c t i o n

    l i s t . a d d ( " d i s a m b i g u a t e " ) ; / / i s t h i s a w o r d ? h o w a b o u t a m b i g u a t e ?

    l i s t . a d d ( " i n p u t t e d " ) ; / / r e a l l y ? w h a t v e r b i f i c a t i o n !

    l i s t . a d d ( " s u b b o o k k e e p e r " ) ; / / n o w t h a t ' s c o o l l o o k i n g !

    w h i l e ( ! l i s t . i s E m p t y ( ) ) / / g a m e l o o p

    {

    t a r g e t W o r d = l i s t . s e l e c t A n y ( ) ; / / s e l e c t i o n

    / / . . . p l a y t h e g a m e u s i n g t a r g e t w o r d . . .

    l i s t . r e m o v e ( t a r g e t W o r d ) ; / / u p d a t e

    }

    Lets consider these lines. One of the first lines (labeled d e c l a r a t i o n ) de-

    W o r d L i s t

    clares a reference to a W o r d L i s t . For a reference to refer to an object, the object

    must be constructed. We require, therefore, a constructor for a W o r d L i s t . Thec o n s t r u c t i o n 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 wordsthat are potentially stored in the list. (Well see later that providing such infor-mation can be useful in designing efficient data structures.) On the next threelines, three (dubious) words are added to the list.

    The w h i l e 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 i s E m p t y method to test this fact. At the beginning of each round of Hangman, a randomword is selected ( s e l e c t A n y ), setting the t a r g e t W o r d reference. To make thingsinteresting, we presume that the s e l e c t A n y method selects a random word eachtime. Once the round is finished, we use the r e m o v e method to remove the wordfrom the word list, eliminating it as a choice in future rounds.

    There are insights here. First, we have said very little about the Hangmangame other than its interaction with our rather abstract list of words. The detailsof the screens appearance, for example, do not play much of a role in under-standing how the W o r d L i s t structure works. We knew that a list was necessaryfor our program, and we considered the program from the point of view of theobject. Second, we dont really know how the W o r d L i s t is implemented. Thewords may be stored in an array, or in a file on disk, or they may use some tech-nology that we dont currently understand. It is only important that we have

    faith that the structure can be implemented. We have sketched out the methodheaders, or signatures