structures andabstractions with javastructures andabstractions withjava thirdedition frank m....

12
Structures and Abstractions with Java Third Edition Frank M. Carrano University of Rhode Island International Edition contributions by Arup Kumar Bhattacharjee RCC Institute of Information Technology Soumen Mukherjee RCC Institute of Information Technology Prentice Hall Boston Columbus Indianpolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

Upload: others

Post on 14-Mar-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Structures and Abstractions

with Java

Third Edition

Frank M. CarranoUniversity of Rhode Island

International Edition contributions by

Arup Kumar BhattacharjeeRCC Institute of Information Technology

Soumen MukherjeeRCC Institute of Information Technology

Prentice Hall

Boston Columbus Indianpolis New York San Francisco Upper Saddle River

Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto

Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

Page 2: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Contents

Introduction 29

Chapter 1 Bags 33

The Bag 34

A Bag's Behaviors 34

Specifying a Bag 35

An Interface 41

Using the ADT Bag 43

Using an ADT Is Like Using a Vending Machine 48

Java Class Library: The Interface Set 49

Chapter 2 Bag Implementations That Use Arrays 55

Using a Fixed-Size Array to Implement the ADT Bag 56

An Analogy 56

A Group ofCore Methods 57

Implementing the Core Methods 5 8

Testing the Core Methods 65

Implementing More Methods 68

Methods That Remove Entries 70

Using Array Resizing to Implement the ADT Bag 78

Resizing an Array 78

A New Implementation of a Bag 81

The Pros and Cons of Using an Array to Implement the ADT Bag 83

Chapter 3 A Bag Implementation That Links Data 89

Linked Data 90

Forming a Chain by Adding to Its Beginning 91

A Linked Implementation ofthe ADT Bag 93

The Private Class Node 93

An Outline ofthe Class Li nkedBag 94

Defining Some Core Methods 95

Testing the Core Methods 99

The Method getFrequencyOf 100

The Method contains 101

Removing an Item from a Linked Chain 102

The Methods remove and cl ear 103

A Class Node That Has Set and Get Methods 106

The Pros and Cons of Using a Chain to Implement the ADT Bag 109

Chapter 4 The Efficiency of Algorithms 115

Motivation 116

Measuring an Algorithm's Efficiency 117

Counting Basic Operations 119

Best, Worst, and Average Cases 121

Big Oh Notation 122

The Complexities ofProgram Constructs 125

Picturing Efficiency 126

The Efficiency ofImplementations ofthe ADT Bag 130

An Array-Based Implementation 130

A Linked Implementation 131

Comparing the Implementations 132

Page 3: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Chapter 5 Stacks 141

Specifications of the ADT Stack 142

Using a Stack to Process Algebraic Expressions 146

A Problem Solved: Checking for Balanced Delimiters in an

Infix Algebraic Expression 147

A Problem Solved: Transforming an Infix Expressionto a Postfix Expression 151

A Problem Solved: Evaluating Postfix Expressions 156

A Problem Solved: Evaluating Infix Expressions 15 8

The Program Stack 160

Java Class Library: The Class Stack 161

Chapter 6 Stack Implementations 169A Linked Implementation 169

An Array-Based Implementation 173

A Vector-Based Implementation 177

Java Class Library: The Class Vector 178

Using a Vector to Implement the ADT Stack 178

Chapter 7 Recursion 185

What Is Recursion? 186

Tracing a Recursive Method 190Recursive Methods That Return a Value 194

Recursively Processing an Array 196

Recursively Processing a Linked Chain 199The Time Efficiency of Recursive Methods 200

The Time Efficiency of countDown 200The Time Efficiency of Computing xP 202

A Simple Solution to a Difficult Problem 203

A Poor Solution to a Simple Problem 208Tail Recursion 210Indirect Recursion 212

Using a Stack Instead of Recursion 213

Chapter 8 An Introduction to Sorting 223

Organizing Java Methods That Sort an Array 224

Selection Sort 226

Iterative Selection Sort 227

Recursive Selection Sort 229The Efficiency of Selection Sort 230

Insertion Sort 231

Iterative Insertion Sort 232Recursive Insertion Sort 234The Efficiency ofInsertion Sort 236Insertion Sort of a Chain ofLinked Nodes 236

Shell Sort 239The Java Code 241

The Efficiency of Shell Sort 242

Comparing the Algorithms 242

Page 4: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Chapter 9 Faster Sorting Methods 249

Merge Sort 250

Merging Arrays 250

Recursive Merge Sort 251

The Efficiency of Merge Sort 253

Iterative Merge Sort 255

Merge Sort in the Java Class Library 255

Quick Sort 256

The Efficiency of Quick Sort 256

Creating the Partition 257

Java Code for Quick Sort 260

Quick Sort in the Java Class Library 262

Radix Sort 263

Pseudocode for Radix Sort 264

The Efficiency ofRadix Sort 265

Comparing the Algorithms 265

Chapter 10 Queues, Deques, and Priority Queues 273

The ADT Queue 274

A Problem Solved: Simulating a Waiting Line 278

A Problem Solved: Computing the Capital Gain in a Sale of Stock 284

Java Class Library: The Interface Queue 287

The ADT Deque 288

A Problem Solved: Computing the Capital Gain in a Sale of Stock 290

Java Class Library: The Interface Deque 291

Java Class Library: The Class ArrayDeque 292

The ADT Priority Queue 293

A Problem Solved: Tracking Your Assignments 294

Java Class Library: The Class Prion' tyQueue 296

Chapter 11 Queue, Deque, and Priority Queue Implementations 301

A Linked Implementation of a Queue 302

An Array-Based Implementation of a Queue 306

A Circular Array 306

A Circular Array with One Unused Location 309

A Vector-Based Implementation ofa Queue 314

Circular Linked Implementations of a Queue 316

A Two-Part Circular Linked Chain 317

Java Class Library: The Class AbstractQueue 322

A Doubly Linked Implementation ofa Deque 323

Possible Implementations of a Priority Queue 327

Chapter 12 Lists 333

Specifications for the ADT List 334

Using the ADT List 340

Java Class Library: The Interface Li st 344

Java Class Library: The Class ArrayLi st 344

Page 5: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Chapter 13 List Implementations That Use Arrays 349

Using an Array to Implement the ADT List 350

An Analogy 350

The Java Implementation 352

The Efficiency of Using an Array to Implement the ADT List 359

Using a Vector to Implement the ADT List 360

Chapter 14 A List Implementation That Links Data 367

Operations on a Chain of Linked Nodes 368

Adding a Node at Various Positions 368

Removing a Node from Various Positions 372

The Private Method getNodeAt 373

Beginning the Implementation 374

The Data Fields and Constructor 375

Adding to the End ofthe List 376

Adding at a Given Position Within the List 377

The Methods i sEmpty and toArray 378

Testing the Core Methods 3 81

Continuing the Implementation 382

A Refined Implementation 384

The Tail Reference 385

The Efficiency of Using a Chain to Implement the ADT List 388

Java Class Library: The Class Li nkedLi st 390

Chapter 15 Iterators 397

What Is an Iterator? 398

The Interface Iterator 399

Using the Interface Ite rator 400

A Separate Class Iterator 405

An Inner Class Iterator 409

A Linked Implementation 409

An Array-Based Implementation 413

Why Are Iterator Methods in Their Own Class? 416

The Interface Listlterator 418

Using the Interface Li stlterator 421

An Array-Based Implementation ofthe Interface Li stlterator 423

The Inner Class 425

Java Class Library: The Interface Iterabl e 430

Iterabl e and for-each loops 431

The Interface Li st Revisited 431

Chapter 16 Sorted Lists 439

Specifications for the ADT Sorted List 440

Using the ADT Sorted List 443

A Linked Implementation 444

The Method add 445

The Efficiency ofthe Linked Implementation 452

An Implementation That Uses the ADT List 452

Efficiency Issues 455

Page 6: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Chapter 17 Inheritance and Lists 461

Using Inheritance to Implement a Sorted List 462

Designing a Base Class 464

Creating an Abstract Base Class 469

An Efficient Implementation of a Sorted List 471

The Method add 471

Chapter 18 Searching 475

The Problem 476

Searching an Unsorted Array 476

An Iterative Sequential Search of an Unsorted Array 477

A Recursive Sequential Search of an Unsorted Array 478

The Efficiency of a Sequential Search of an Array 480

Searching a Sorted Array 480

A Sequential Search ofa Sorted Array 480

A Binary Search of a Sorted Array 481

Java Class Library: The Method bi narySearch 486

The Efficiency of a Binary Search of an Array 486

Searching an Unsorted Chain 488

An Iterative Sequential Search of an Unsorted Chain 488

A Recursive Sequential Search ofan Unsorted Chain 489

The Efficiency of a Sequential Search of a Chain 490

Searching a Sorted Chain 490

A Sequential Search of a Sorted Chain 490

A Binary Search of a Sorted Chain 490

Choosing a Search Method 491

Chapter 19 Dictionaries 499

Specifications for the ADT Dictionary 500

A Java Interface 504

Iterators 505

Using the ADT Dictionary 506

A Problem Solved: A Directory of Telephone Numbers 507

A Problem Solved: The Frequency ofWords 512

A Problem Solved: A Concordance ofWords 516

Java Class Library: The Interface Map 518

Chapter 20 Dictionary Implementations 525

Array-Based Implementations 526

An Unsorted Array-Based Dictionary 526

A Sorted Array-Based Dictionary 531

Vector-Based Implementations 536

Linked Implementations 540

An Unsorted Linked Dictionary 542

A Sorted Linked Dictionary 542

Chapter 21 Introducing Hashing 551

What Is Hashing? 552

Hash Functions 555

Computing Hash Codes 555

Compressing a Hash Code into an Index for the Hash Table 558

Page 7: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Resolving Collisions 559

Open Addressing with Linear Probing 559

Open Addressing with Quadratic Probing 565

Open Addressing with Double Hashing 565

A Potential Problem with Open Addressing 567

Separate Chaining 567

Chapter 22 Hashing as a Dictionary Implementation 575

The Efficiency of Hashing 576

The Load Factor 576

The Cost of Open Addressing 577

The Cost of Separate Chaining 579

Rehashing 580

Comparing Schemes for Collision Resolution 581

A Dictionary Implementation That Uses Hashing 582

Entries in the Hash Table 582

Data Fields and Constructors 583

The Methods getVal ue, remove, and add 585

Iterators 590

Java Class Library: The Class HashMap 592

Java Class Library: The Class HashSet 592

Chapter 23 Trees 597

Tree Concepts 598

Hierarchical Organizations 598

Tree Terminology 600

Traversals of a Tree 604

Traversals of a Binary Tree 604

Traversals of a General Tree 607

Java Interfaces for Trees 607

Interfaces for All Trees 608

An Interface for Binary Trees 608

Examples ofBinary Trees 610

Expression Trees 610

Decision Trees 612

Binary Search Trees 616

Heaps 618

Examples of General Trees 621

Parse Trees 621

Game Trees 621

Chapter 24 Tree Implementations 631

The Nodes in a Binary Tree 632

An Interface for a Node 633

An Implementation of Bi naryNode 634

An Implementation of the ADT Binary Tree 635

Creating a Basic Binary Tree 636The Method pri vateSetTree 637Accessor and Mutator Methods 640

Computing the Height and Counting Nodes 641

Traversals 642

Page 8: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

An Implementation of an Expression Tree 647

General Trees 649

A Node for a General Tree 649

Using a Binary Tree to Represent a General Tree 650

Chapter 25 A Binary Search Tree Implementation 657

Getting Started 658

An Interface for the Binary Search Tree 659

Duplicate Entries 661

Beginning the Class Definition 662

Searching and Retrieving 663

Traversing 665

Adding an Entry 665

A Recursive Implementation 666

An Iterative Implementation 670

Removing an Entry 671

Removing an Entry Whose Node Is a Leaf 672

Removing an Entry Whose Node Has One Child 672

Removing an Entry Whose Node Has Two Children 673

Removing an Entry in the Root 676

A Recursive Implementation 677

An Iterative Implementation 680

The Efficiency of Operations 684

The Importance of Balance 685

The Order in Which Nodes Are Added 686

An Implementation of the ADT Dictionary 687

Chapter 26 A Heap Implementation 701

Reprise: The ADT Heap 702

Using an Array to Represent a Heap 702

Adding an Entry 705

Removing the Root 708

Creating a Heap 711

Heap Sort 714

Chapter 27 Balanced Search Trees 723AVL Trees 724

Single Rotations 724

Double Rotations 727

Implementation Details 731

2-3 Trees 735

Searching a 2-3 Tree 736

Adding Entries to a 2-3 Tree 737

Splitting Nodes During Addition 739

2-4 Trees 740

Adding Entries to a 2-4 Tree 741

Comparing AVL, 2-3, and 2-4 Trees 743

Red-Black Trees 744

Properties ofa Red-Black Tree 745

Adding Entries to a Red-Black Tree 746

Java Class Library: The Class TreeMap 752

B-Trees 752

Page 9: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Chapter 28 Graphs 759

Some Examples and Terminology 760

Road Maps 760

Airline Routes 763

Mazes 764

Course Prerequisites 764

Trees 765

Traversals 765

Breadth-First Traversal 766

Depth-First Traversal 768

Topological Order 769

Paths 772

Finding a Path 772

The Shortest Path in an Unweighted Graph 772

The Shortest Path in a Weighted Graph 775

Java Interfaces for the ADT Graph 779

Chapter 29 Graph Implementations 789

An Overview ofTwo Implementations 790

The Adjacency Matrix 790

The Adjacency List 791

Vertices and Edges 792

Specifying the Class Vertex 793

The Inner Class Edge 795

Implementing the Class Vertex 796

An Implementation ofthe ADT Graph 800

Basic Operations 800

Graph Algorithms 803

Chapter 30 Mutable, Immutable, and Cloneable Objects Online

Mutable and Immutable Objects 30-2

Creating a Read-Only Class 30-4

Companion Classes 30-6

Cloneable Objects 30-8

Cloning an Array 30-14

Cloning a Chain 30-16

A Sorted List ofClones 30-19

Appendices

A. Java Essentials A-l

Introduction A-2

Applications and Applets A-2

Objects and Classes A-3

A First Java Application Program A-3

Java Basics A-5

Identifiers A-5

Reserved Words A-6

Variables A-6

Primitive Types A-7

Constants A-7

Page 10: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Assignment Statements A-8

Assignment Compatibilities A-9

Type Casting A-9

Arithmetic Operators and Expressions A-10

Parentheses and Precedence Rules A-11

Increment and Decrement Operators A-12

Special Assignment Operators A-13

Named Constants A-14

The Class Math A-15

Simple Input and Output Using the Keyboard and Screen A-15

Screen Output A-15

Keyboard Input Using the Class Scanner A-17

The i f-el se Statement A-19

Boolean Expressions A-20

Nested Statements A-23

Multiway if-else Statements A-24

The Conditional Operator (Optional) A-25

The swi tch Statement A-26

Enumerations A-28

Scope A-30

Loops A-30The whi 1 e Statement A-31

The for Statement A-32

The do-while Statement A-34Additional Loop Information A-35

The Class String A-36

Characters Within Strings A-36Concatenation of Strings A-37

String Methods A-38

The Class StringBuilder A-40

Using Scanner to Extract Pieces of a String A-42

Arrays A-44

Array Parameters and Returned Values A-46

Initializing Arrays A-47

Array Index Out of Bounds A-47

Use of = and == with Arrays A-47

Arrays and the For-Each Loop A-48Multidimensional Arrays A-49

Wrapper Classes A-51

B. Java Classes B-1

Objects and Classes B-1

Using the Methods in a Java Class B-3

References and Aliases B-4

Defining a Java Class B-5

Method Definitions B-7

Arguments and Parameters B-9

Passing Arguments B-9

A Definition ofthe Class Name B-13

Page 11: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Constructors B-15

The Method toStri ng B-17

Methods That Call Other Methods B-17

Methods That Return an Instance ofTheir Class B-19

Static Fields and Methods B-19

Overloading Methods B-21

Enumeration as a Class B-22

Packages B-25

The Java Class Library B-25

Generic Data Types B-26

C. Creating Classes from Other Classes C-1

Composition C-2

Adapters C-4

Inheritance C-5

Invoking Constructors from Within Constructors C-9

Private Fields and Methods of the Superclass C-10

Protected Access C-11

Overriding and Overloading Methods C-11

Multiple Inheritance C-16

Type Compatibility and Superclasses C-16

The Class Object C-18

Abstract Classes and Methods C-19

Polymorphism C-21

D. Designing Classes D-1

Encapsulation D-2

Specifying Methods D-4

Comments D-4

Preconditions and Postconditions D-5

Assertions D-6

Java Interfaces D-7

Writing an Interface D-8

Implementing an Interface D-10

An Interface as a Data Type D-11

Generic Types Within an Interface D-12

Extending an Interface D-14

Interfaces Versus Abstract Classes D-15

Named Constants Within an Interface D-17

Choosing Classes D-18

Identifying Classes D-20

CRC Cards D-20

The Unified Modeling Language D-21

Reusing Classes D-23

E. Handling Exceptions E-1

The Basics E-2

Handling an Exception E-4

Postpone Handling: The throws Clause E-4

Handle ItNow: The try-catch Blocks E-5

Multiple catch Blocks E-6

Page 12: Structures andAbstractions with JavaStructures andAbstractions withJava ThirdEdition Frank M. Carrano UniversityofRhode Island International Edition contributions by Arup KumarBhattacharjee

Throwing an Exception E-8

Programmer-Defined Exception Classes E-9

Inheritance and Exceptions E-14

The finally Block E-15

F. File Input and Output F-1Preliminaries F-2

Why Files? F-2

Streams F-2

The Kinds ofFiles F-3

File Names F-3

Text Files F-3

Creating a Text File F-3

Reading a Text File F-8

Changing Existing Data in a Text File F-12

Defining a Method to Open a Stream F-13

Binary Files F-13

Creating a Binary File ofPrimitive Data F-14

Reading a Binary File ofPrimitive Data F-18

Strings in a Binary File F-20

Object Serialization F-23

G. Documentation and Programming Style G-1

Naming Variables and Classes G-1

Indenting G-2

Comments G-2

Single-Line Comments G-3

Comment Blocks G-3When to Write Comments G-3

Java Documentation Comments G-3

Running j avadoc G-5

Glossary Online

Index I-l