Usin§Java - GBV

16
Data Structures &r Other Objects Usin §Java MICHAEL MAIN University of Colorado at Boulder W ADDISON-WESLEY Addison-Wesley is an imprint of Addison Wesley Longman, Inc. Reading, Massachusetts Harlow, England Menlo Park, California Berkeley, California Don Mills, Ontario Sydney Bonn Amsterdam Tokyo Mexico City

Transcript of Usin§Java - GBV

Page 1: Usin§Java - GBV

Data Structures &r Other Objects

Usin§Java

MICHAEL MAIN

University of Colorado at Boulder

W ADDISON-WESLEY Addison-Wesley is an imprint

of Addison Wesley Longman, Inc.

Reading, Massachusetts Harlow, England Menlo Park, California

Berkeley, California Don Mills, Ontario Sydney Bonn Amsterdam

Tokyo Mexico City

Page 2: Usin§Java - GBV

Chapter 1 The Phases of Software Development 1 1.1 Specification, Design, Implementation 3

Design Technique: Decomposing the Problem 4 How to Write a Specification for a Java Method 5 Throwing an Exception to Indicate a Failed Precondition 8 Programming Tip: How and When to Throw Exceptions 9 Programming Tip: Use Final Variables to Improve Clarity 10 The Method for Printing a Number 11 Self-Test Exercises 13

1.2 Running Time Analysis 18 The Stair-Counting Problem 18 Big-0 Notation 23 Time Analysis of Java Methods 25

Worst-Case, Average-Case and Best-Case Analyses 27 Self-Test Exercises 27

1.3 Testing and Debugging 28 Choosing Test Data 28 Boundary Values 28 Fully Exercising Code 30 Programming Tip: How to Debug 30 Self-Test Exercises 31

Page 3: Usin§Java - GBV

Chapter Summary 31 Solutions to Self-Test Exercises 32

Chapter 2 Abstract Data Types and Java Classes 35 2.1 Classes and Their Members 36

Programming Example: The Throttle Class 36 Defining a New Class 37 Instance Variables 38 Constructors 38 No-Arguments Constructors 40

Methods 40 Accessor Methods 40 Pitfall: Integer Division Throws Away the Fractional Part 41 Programming Tip: Use the Boolean Type for True-or-False

Values 42 Modification Methods 42 Pitfall: Potential Arithmetic Overflows 44 Methods May Activate Other Methods 47 Programming Tip: Private Versus Public 47 Self-Test Exercises 47

2.2 Using a Class 48 Creating and Using Objects 48 A Program with Several Throttle Objects 50 Null References 50 Pitfall: Null Pointer Exception 51 Assignment Statements with Reference Variables 51

Clones 54 Testing for Equality 54 Terminology Controversy: "The Throttle That t Refers To" 56 Self-Test Exercises 56

2.3 Packages 56 Declaring a Package 57

The Import Statement to Use a Package 59 The JCL Packages 59 More about Public, Private, and Package Access 61 Self-Test Exercises 61

Page 4: Usin§Java - GBV

xx Contents

2.4 Parameters, Equals Methods, and Clones 61 The Location Class 62 Static Methods 68 Parameters That Are Objects 69 The Return Value of a Method May Be an Object 70 Programming Tip: How to Choose the Names of Methods 72 Java's Object Type 72 Using and Implementing an Equals Method 73 Pitfall: Class Cast Exception 75 Every Class Has an Equals Method 76 Using and Implementing a Clone Method 76 Pitfall: A Typecast Is Needed to Use the Clone Return Value 77 Programming Tip: Always Use super.clone for Your Clone

Methods 80 Programming Tip: When to Throw a Runtime Exception 81 A Demonstration Program for the Location Class 81 What Happens When a Parameter Is Changed within a Method? 83 Self-Test Exercises 85

Chapter Summary 86 Solutions to Self-Test Exercises 87 Programming Projects 88

Chapter 3 Collection Classes 95 3.1 A Review of Java Arrays 96

Pitfall: Exceptions That Arise from Arrays 97 The Length of an Array 97 Assignment Statements with Arrays 98 Clones of Arrays 99 Array Parameters 100 Self-Test Exercises 101

3.2 An ADT for a Bag of Integers 101 The Bag ADT—Specification 102 OutOfMemoryError and Other Limitations for Collection

Classes 106 The IntArrayBag Class—Specification 106 The IntArrayBag Class—Demonstration Program 110

Page 5: Usin§Java - GBV

The IntAr rayBag Class—Design 113 The Invariant of an ADT 114 The IntAr rayBag ADT—Implementation 115 Programming Tip: Cloning a Class That Contains an Array 124 The Bag ADT—Putting the Pieces Together 125 Programming Tip: Document the ADT Invariant in the

Implementation File 129 The Bag ADT—Testing 130 Pitfall: An Object Can Be an Argument to Its Own Method 130 The Bag ADT—Analysis 131 Self-Test Exercises 132

3.3 Programming Project: The Sequence ADT 133 The Sequence ADT—Specification 133 The Sequence ADT—Documentation 137 The Sequence ADT—Design 142 The Sequence ADT—Pseudocode for the Implementation 143 Self-Test Exercises 146

3.4 Applets for Interactive Testing 146 Six Parts of a Simple Interactive Applet 150 How to Compile and Run an Applet 163 Beyond the i ni t Method 164 Self-Test Exercises 164

Chapter Summary 165 Solutions to Self-Test Exercises 166 Programming Projects 168

Chapter 4 Linked Lists 171 4.1 Fundamentals of Linked Lists 172

Declaring a Class for Nodes 172 Head Nodes, Tail Nodes 173 The Null Reference 174 Pitfall: Null Pointer Exceptions with Linked Lists 174 Self-Test Exercises 175

4.2 Methods for Manipulating Nodes 175 Constructor for the Node Class 175 Getting and Setting the Data and Link of a Node 176

Page 6: Usin§Java - GBV

xxii Contents

Public versus Private Instance Variables 177 Adding a New Node at the Head of a Linked List 177 Removing a Node from the Head of a Linked List 179 Adding a New Node That Is Not at the Head 181 Removing a Node That Is Not at the Head 184 Pitfall: Null Pointer Exceptions with removeNodeAfter 187 Self-Test Exercises 187

4.3 Manipulating an Entire Linked List 188 Computing the Length of a Linked List 189 Programming Tip: How to Traverse a Linked List 192 Pitfall: Forgetting to Test the Empty List 193 Searching for an Element in a Linked List 193 Finding a Node by Its Position in a Linked List 194 Copying a Linked List 196

A Second Copy Method, Returning Both Head and Tail References 200

Programming Tip: A Method Can Return an Array 201 Copying Part of a Linked List 202 Using Linked Lists 203 Self-Test Exercises 210

4.4 The Bag ADT with a Linked List 211 Our Second Bag—Specification 211 The g rab Method 214

Our Second Bag—Class Declaration 214 The Second Bag—Implementation 215 Programming Tip: Cloning a Class That Contains a Linked

List 218 Programming Tip: How to Choose between Different

Approaches 220 The Second Bag—Putting the Pieces Together 224 Self-Test Exercises 227

4.5 Programming Project: The Sequence ADT with a Linked List 227 The Revised Sequence ADT—Design Suggestions 227 The Revised Sequence ADT—Clone Method 230 Self-Test Exercises 233

4.6 Arrays vs. Linked Lists vs. Doubly Linked Lists 234

Page 7: Usin§Java - GBV

Contents xxiii

Making the Decision 235 Self-Test Exercises 235

Chapter Summary 236 Solutions to Self-Test Exercises 236 Programming Projects 238

Chapter 5 Java Objects and Iterators 241 5.1 Java's Object Type 242

Widening Conversions 242 Narrowing Conversions 243 Wrapper Classes 245 Self-Test Exercises 246

5.2 A Bag of Objects 247 Counting the Occurrences of an Object 247 The Collection Is Really a Collection of References to Objects 249 Five Steps for Converting a Collection Class to Hold Objects 250 Deep Clones for Collection Classes 251 Using the Bag of Objects 259 Details of the Story-Writing Program 262 Self-Test Exercises 262

5.3 JCL Collections and Nodes of Objects 263 Vectors and Other JCL Collections 263 Nodes That Contain Object Data 263 Pitfall: Misuse of the equal s Method 264 Other Collections That Use Linked Lists 266 Self-Test Exercises 266

5.4 Iterators 266 Interfaces 266 The Meaning of the Cloneable Interface 267 The Iterator Interface 268 The Lister Class 269 A Collection Can Provide an Iterator for Its Own Elements 272 Implementing the Bag of Objects Using a Linked List and an i t e r a t o r

Method 272 Programming Tip: External Iterators versus Internal Iterators 273 Summary of the Four Bag Implementations 274

Page 8: Usin§Java - GBV

xxiv Contents

Self-Test Exercises 274 Chapter Summary 275 Solutions to Self-Test Exercises 275 Programming Projects 277

Chapter^ Stacks 279 6.1 Introduction to Stacks 279

The Stack ADT—Specification 281 Writing Nine Stack Classes at Once 283 Programming Example: Reversing a Word 283 Self-Test Exercises 284

6.2 Stack Applications 284 Programming Example: Balanced Parentheses 285 Programming Tip: The Switch Statement 288 Evaluating Arithmetic Expressions 288 Evaluating Arithmetic Expressions—Specification 289 Evaluating Arithmetic Expressions—Design 289 Using the readAndEval uate Method 294 Implementation of readAndEval ua te 294 Evaluating Arithmetic Expressions—Testing and Analysis 298 Evaluating Arithmetic Expressions—Enhancements 299 Self-Test Exercises 299

6.3 Implementations of the Stack ADT 300 Array Implementation of a Stack 300 Linked List Implementation of a Stack 306 Self-Test Exercises 309

6.4 More Complex Stack Applications 310 Evaluating Postfix Expressions 310 Translating Infix to Postfix Notation 313 Using Precedence Rules in the Infix Expression 315 Correctness of the Conversion from Infix to Postfix 318 Self-Test Exercises 319

Chapter Summary 319 Solutions to Self-Test Exercises 320 Programming Projects 321

Page 9: Usin§Java - GBV

Chapter 7 Queues 325 7.1 Introduction to Queues 325

The Queue ADT 327 Uses for Queues 327 Self-Test Exercises 329

7.2 Queue Applications 330 Programming Example: Palindromes 330 Self-Test Exercises 332 Programming Example: Car Wash Simulation 333 Car Wash Simulation—Specification 333 Car Wash Simulation—Design 334 Car Wash Simulation—Implementing the Car Wash Classes 338 Car Wash Simulation—Implementing the Simulation Method 339 Self-Test Exercises 339

7.3 Implementations of the Queue ADT 347 Array Implementation of a Queue 347 Programming Tip: Use Helper Methods to Improve Clarity 350 Linked List Implementation of a Queue 357 Pitfall: Forgetting Which End Is Which 362 Self-Test Exercises 362

7.4 Priority Queues 363 Priority Queue ADT—Specification 363 Priority Queue ADT—An Implementation That Uses an Ordinary

Queue 365 Priority Queue ADT—A Direct Implementation 366 Self-Test Exercises 366

Chapter Summary 367 Solutions to Self-Test Exercises 367 Programming Projects 368

Chapter 8 Recursive Thinking 371 8.1 Recursive Methods 372

A First Example of Recursive Thinking 372 Tracing Recursive Calls 374 Programming Example: An Extension of wri t eVe r t i cal 375

Page 10: Usin§Java - GBV

xxvi Contents

A Closer Look at Recursion 377 General Form of a Successful Recursive Method 380 Self-Test Exercises 381

8.2 Studies of Recursion: Fractals and Mazes 382 Programming Example: Generating Random Fractals 382 A Method for Generating Random Fractals—Specification 383 The Stopping Case for Generating a Random Fractal 388 Putting the Random Fractal Method in an Applet 388 Programming Example: Traversing a Maze 391 Traversing a Maze—Specification 391 Traversing a Maze—Design 392 Traversing a Maze—Implementation 393 The Recursive Pattern of Exhaustive Search with Backtracking 397 Programming Example: The Teddy Bear Game 398 Self-Test Exercises 398

8.3 Reasoning about Recursion 400 How to Ensure That There is No Infinite Recursion in the More

General Case 403

Inductive Reasoning about the Correctness of a Recursive Method 405 Recursion versus Loops 406 Programming Tip: Avoid Tail Recursion 408 Self-Test Exercises 408

Chapter Summary 409 Solutions to Self-Test Exercises 409 Programming Projects 411

Chapter 9 Trees 415 9.1 Introduction to Trees 416

Binary Trees 416 Binary Taxonomy Trees 419 General Trees 420 Self-Test Exercises 421

9.2 Tree Representations 421 Array Representation of Complete Binary Trees 421 Representing a Binary Tree with a Class for Nodes 424 Self-Test Exercises 426

Page 11: Usin§Java - GBV

Contents xxvii

9.3 A Class for Binary Tree Nodes 426 Programming Example: Animal Guessing 435 Animal Guessing Program—Design and Implementation 437 Animal Guessing Program—Improvements 443 Self-Test Exercises 443

9.4 Tree Traversals 446 Traversals of Binary Trees 446 Printing a Tree with an Indentation to Show the Depths 450 BTNode, IntBTNode, and Other Classes 451 Self-Test Exercises 452

9.5 Binary Search Trees 460 The Binary Search Tree Storage Rules 460 The Binary Search Tree Bag—Implementation of Some Simple

Methods 465 Counting the Occurrences of an Element in a Binary Search Tree 466 Adding a New Element to a Binary Search Tree 467 Removing an Element from a Binary Search Tree 468 The addAl 1 and uni on Methods 472 Pitfall: Violating the addTree Precondition 473 Time Analysis and an Internal Iterator 475 Self-Test Exercises 475

Chapter Summary 476 Solutions to Self-Test Exercises 476 Programming Projects 479

Chapter 10 Tree Projects 483 10.1 Heaps 484

The Heap Storage Rules 484 The Priority Queue ADT with Heaps 485 Adding an Element to a Heap 485 Removing an Element from a Heap 487 Self-Test Exercises 490

10.2 B-Trees 490 The Problem of Unbalanced Trees 490 The B-Tree Rules 491 An Example B-Tree 492

Page 12: Usin§Java - GBV

xxviii Contents

The Set ADT with B-Trees 493 Searching for an Element in a B-Tree 498 Programming Tip: Private Methods to Simplify Implementations 500 Adding an Element to a B-Tree 500 The Loose Addition Operation for a B-Tree 501 A Private Method to Fix an Excess in a Child 503 Back to the add Method 504 Employing Top-Down Design 506 Removing an Element from a B-Tree 506 The Loose Removal from a B-Tree 507 A Private Method to Fix a Shortage in a Child 509 Removing the Biggest Element from a B-Tree 512 Programming Tip: Write and Test Small Pieces 512 External B-Trees 513

Self-Test Exercises 514

10.3 Trees, Logs, and Time Analysis 515 Time Analysis for Binary Search Trees 516 Time Analysis for Heaps 516 Logarithms 519 Logarithmic Algorithms 520 Self-Test Exercises 520

Chapter Summary 520 Solutions to Self-Test Exercises 521 Programming Projects 523

Chapter 11 Searching 525 11.1 Serial Search and Binary Search 526

Serial Search 526 Serial Search—Analysis 526 Binary Search 528 Binary Search—Design 529

Pitfall: Common Indexing Errors in Binary Search Implementations 532

Binary Search—Analysis 532 Self-Test Exercises 536

11.2 Open-Address Hashing 537 Introduction to Hashing 537

Page 13: Usin§Java - GBV

Contents xxix

Non-Integer Keys and Java's hashCode Method 539 The Table ADT—Specification 540 The Table ADT—Design 542 The Table ADT—Implementation 544 A Practical Illustration of Open-Address Hashing 550 Choosing a Hash Function to Reduce Collisions 552 Double Hashing to Reduce Clustering 552 Self-Test Exercises 554

11.3 Using Java's Hashtable Class 554

11.4 Chained Hashing 555 Self-Test Exercises 558

11.5 Time Analysis of Hashing 558 The Load Factor of a Hash Table 558 Self-Test Exercises 561

Chapter Summary 561 Solutions to Self-Test Exercises 562 Programming Projects 564

Chapter 12 Sorting 567 12.1 Quadratic Sorting Algorithms 568

Selectionsort—Specification 568 Selectionsort—Design 568 Selectionsort—Testing 572 Selectionsort—Analysis 573 Insertionsort 575 Programming Tip: Rough Estimates Suffice for Big-0 Insertionsort—Analysis 579

Self-Test Exercises 582

12.2 Recursive Sorting Algorithms 582 Divide-and-Conquer Using Recursion 582 Mergesort 583

The Merge Function 584 Mergesort—Analysis 591 Mergesort for Files 593 Quicksort 593 The Partition Method 596 Quicksort—Analysis 599

Page 14: Usin§Java - GBV

Quicksort—Choosing a Good Pivot Element 601

Self-Test Exercises 601

12.3 An 0(n log n) Algorithm Using a Heap 602 Heapsort 602 Making the Heap 609 Reheapification Downward 610 Heapsort—Analysis 611 Self-Test Exercises 612

Chapter Summary 613 Solutions to Self-Test Exercises 613 Programming Projects 614

Chapter 13 Software Reuse with Extended Classes 617 13.1 Extended Classes 618

How to Declare an Extended Class 620 The Constructors of an Extended Class 622 Using an Extended Class 622 Overriding Inherited Methods 624 Programming Tip: Make the Overriding Method Activate the

Original 624 Widening Conversions for Extended Classes 626 Narrowing Conversions for Extended Classes 627 Self-Test Exercises 628

13.2 Simulation of an Ecosystem 628 Programming Tip: When to Use an Extended Class 629 Implementing Part of the Organism Object Hierarchy 629 The Organism Class 629 The Animal Class: An Extended Class with New Private Instance

Variables 633 How to Provide a New Constructor for an Extended Class 633 The Other Animal Methods 635 Self-Test Exercises 636 The Herbivore Class 640 The Pond Life Simulation Program 643 Pondlife—Implementation Details 648 Using the Pond Model 648 Self-Test Exercises 649

Page 15: Usin§Java - GBV

Contents xxxi

13.3 Using Extended Classes for ADTs 650 Pushing and Popping for the Extended Stack Class 654 Self-Test Exercises 658

Chapter Summary 658 Further Reading 658 Solutions to Self-Test Exercises 659 Programming Projects 661

Chapter 14 Graphs 663 14.1 Graph Definitions 663

Undirected Graphs 664 Programming Example: Undirected State Graphs 665 Directed Graphs 668 More Graph Terminology 669 Airline Routes Example 670 Self-Test Exercises 671

14.2 Graph Implementations 671 Representing Graphs with an Adjacency Matrix 671 Using a Two-Dimensional Array to Store an Adjacency Matrix 672 Representing Graphs with Edge Lists 673 Representing Graphs with Edge Sets 674 Which Representation Is Best? 674 Programming Example: Labeled Graph ADT 675 The Graph Constructor and si ze Method 676 Methods for Manipulating Edges 677 Methods for Manipulating Vertex Labels 678 Labeled Graph ADT—Implementation 678 Self-Test Exercises 684

14.3 Graph Traversals 684 Depth-First Search 685 Breadth-First Search 689 Depth-First Search—Implementation 691 Breadth-First Search—Implementation 693 Self-Test Exercises 694

14.4 Path Algorithms 694 Determining Whether a Path Exists 694 Graphs with Weighted Edges 694

Page 16: Usin§Java - GBV

xxxii Contents

Shortest Distance Algorithm 695 Shortest Path Algorithm 705

Self-Test Exercises 706 Chapter Summary 707 Solutions to Self-Test Exercises 707 Programming Projects 709

Appendixes A Java's Primitive Types and Arithmetic Overflow 711

B Java Input and Output 714

C Throwing and Catching Java Exceptions 732

D Java's Vector and Hashtable Classes 737

E A Class for Nodes in a Linked List 741

F A Class for a Bag of Objects 749

G Further Big-0 Notation 755

H Javadoc 757

Index 765