Koffman-index.indd 660 10/30/2015 7:27:45 PM
DATA STRUCTURES Abstraction and Design
Using Java THIRD EDITION
ELLIOT B. KOFFMAN Temple University
PAUL A. T. WOLFGANG Temple University
Koffman-ffirs.indd 1 11/3/2015 9:04:31 PM
VICE PRESIDENT & DIRECTOR Laurie Rosatone SENIOR DIRECTOR Don Fowley EXECUTIVE EDITOR Brian Gambrel DEVELOPMENT EDITOR Jennifer Lartz ASSISTANT Jessy Moor PROJECT MANAGER Gladys Soto PROJECT SPECIALIST Nichole Urban PROJECT ASSISTANT Anna Melhorn MARKETING MANAGER Dan Sayre ASSISTANT MARKETING MANAGER Puja Katarawala ASSOCIATE DIRECTOR Kevin Holm SENIOR CONTENT SPECIALIST Nicole Repasky PRODUCTION EDITOR Rajeshkumar Nallusamy PHOTO RESEARCHER Amanda Bustard COVER PHOTO CREDIT © Robert Davies/Shutterstock
This book was set in 10/12 pt SabonLTStd-Roman by SPiGlobal and printed and bound by Lightning Source Inc.
Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more than 200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is built on a foundation of principles that include responsibility to the communities we serve and where we live and work. In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental, social, economic, and ethical challenges we face in our business. Among the issues we are addressing are carbon impact, paper specifications and procurement, ethical conduct within our business and among our vendors, and community and charitable support. For more information, please visit our website: www.wiley.com/go/citizenship.
Copyright © 2016, 2010 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit- ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authori- zation through payment of the appropriate per‐copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923 (Web site: www.copyright.com). Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030‐5774, (201) 748‐6011, fax (201) 748‐6008, or online at: www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next academic year. These copies are licensed and may not be sold or transferred to a third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instructions and a free of charge return shipping label are available at: www.wiley.com/go/ returnlabel. If you have chosen to adopt this textbook for use in your course, please accept this book as your complimentary desk copy. Outside of the United States, please contact your local sales representative.
ISBN: 978-1-119-23914-7 (PBK) ISBN: 978-1-119-22307-8 (EVALC)
Library of Congress Cataloging-in-Publication Data Koffman, Elliot B. [Objects, abstraction, data structures and design using Java] Data structures : abstraction and design using Java / Elliot B. Koffman, Temple University, Paul A.T. Wolfgang, Temple University. — Third edition. pages cm Original edition published under title: Objects, abstraction, data structures and design using Java. Includes index. ISBN 978-1-119-23914-7 (pbk.) 1. Data structures (Computer science) 2. Java (Computer program language) 3. Object-oriented programming (Computer science) 4. Application program interfaces (Computer software) I. Wolfgang, Paul A. T. II. Title.
QA76.9.D35K58 2016 005.7'3—dc23
2015036861
Printing identification and country of origin will either be included on this page and/or the end of the book. In addition, if the ISBN on this page and the back cover do not match, the ISBN on the back cover should be considered the correct ISBN.
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
Koffman-ffirs.indd 2 11/4/2015 3:00:52 PM
http://www.wiley.com/go/citizenship
http://www.copyright.com
http://www.wiley.com/go/permissions
http://www.wiley.com/goreturnlabel
Preface Our goal in writing this book was to combine a strong emphasis on problem solving and software design with the study of data structures. To this end, we discuss applications of each data structure to motivate its study. After providing the specification (interface) and the implementation (a Java class), we then cover case studies that use the data structure to solve a significant problem. Examples include maintaining an ordered list, evaluating arithmetic expressions using a stack, finding the shortest path through a maze, and Huffman coding using a binary tree and a priority queue. In the implementation of each data structure and in the solutions of the case studies, we reinforce the message “Think, then code” by performing a thorough analysis of the problem and then carefully designing a solution (using pseudo‐ code and UML class diagrams) before the implementation. We also provide a performance analysis when appropriate. Readers gain an understanding of why different data structures are needed, the applications they are suited for, and the advantages and disadvantages of their possible implementations.
Intended Audience This book was written for anyone with a curiosity or need to know about data structures, those essential elements of good programs and reliable software. We hope that the text will be useful to readers with either professional or educational interests.
It is intended as a textbook for the second programming course in a computing curriculum involving the study of data structures, especially one that emphasizes Object‐Oriented Design (OOD). The text could also be used in a more‐advanced course in algorithms and data struc- tures. Besides coverage of the basic data structures and algorithms (lists, stacks, queues, trees, recursion, sorting), there are chapters on sets and maps, balanced binary search trees, graphs, and an online appendix on event‐oriented programming. Although we expect that most read- ers will have completed a first programming course in Java, there is an extensive review chapter (included as an appendix) for those who may have taken a first programming course in a different language, or for those who need a refresher in Java.
Emphasis on the Java Collections Framework The book focuses on the interfaces and classes in the Java Collections Framework. We begin the study of a new data structure by specifying an abstract data type as an interface, which we adapt from the Java API. Readers are encouraged throughout the text to use the Java Collections Framework as a resource for their programming.
Our expectation is that readers who complete this book will be familiar with the data struc- tures available in the Java Collections Framework and will be able to use them in their future programming. However, we also expect that they will want to know how the data structures are implemented, so we provide thorough discussions of classes that implement these data structures. Each class follows the approach taken by the Java designers where appropriate. However, when their industrial‐strength solutions appear to be too complicated for beginners to understand, we have provided simpler implementations but have tried to be faithful to their approach.
Koffman-preface.indd 3 10/20/2015 3:02:35 PM
iv Preface
Think, then Code To help you “Think, then code” we discuss problem solving and introduce appropriate soft- ware design tools throughout the textbook. For example, Chapter 1 focuses on OOD and Class Hierarchies. It introduces the Uniform Modeling Language (also covered in Appendix B) to document an OOD. It introduces the use of interfaces to specify abstract data types and to facilitate contract programming and describes how to document classes using Javadoc‐style comments. There is also coverage of exceptions and exception handling. Chapter 2 intro- duces the Java Collections Framework and focuses on the List interface, and it shows how to use big‐O notation to analyze program efficiency. In Chapter 3, we cover different testing strategies in some detail including a discussion of test‐driven design and the use of the JUnit program to facilitate testing.
Features of the Third Edition We had two major goals for the third edition. The first was to bring the coverage of Java up to Java 8 by introducing new features of Java where appropriate. For example, we use the Java 7 diamond operator when creating new Collection objects. We use the Java 8 StringJoiner in place of the older StringBuilder for joining strings.
A rather significant change was to introduce Java 8 lambda expressions and functional inter- faces as a way to facilitate functional programming in Java in a new Section 6.4. Using these features significantly improved the code.
The second major goal was to provide additional emphasis on testing and debugging. To facilitate this, we moved our discussion of testing and debugging from an appendix to Chapter 3 and expanded our coverage of testing including more discussion of JUnit. We also added a new section that introduced test‐driven development.
A third goal was to ease the transition to Java for Python programmers. When introducing Java data structures (for example, arrays, lists, sets, and maps), we compared them to equiva- lent Python data structures.
Other changes to the text included reorganizing the chapter on lists and moving the discussion of algorithm analysis to the beginning of the chapter so that big‐O notation could be used to compare the efficiency of different List implementations. We also combined the chapters on stacks and queues and increased our emphasis on using Deque as an alternative to the legacy Stack class. We also added a discussion of Timsort, which is used in Java 8, to the chapter on sorting algorithms. Finally, some large case studies and an appendix were moved to online supplements.
Case Studies We illustrate OOD principles in the design and implementation of new data structures and in the solution of approximately 20 case studies. Case studies follow a five‐step process (prob- lem specification, analysis, design, implementation, and testing). As is done in industry, we sometimes perform these steps in an iterative fashion rather than in strict sequence. Several case studies have extensive discussions of testing and include methods that automate the test- ing process. Some case studies are revisited in later chapters, and solutions involving different data structures are compared. We also provide additional case studies on the Web site for the textbook (www.wiley.com/college/koffman), including one that illustrates a solution to the same problem using several different data structures.
Koffman-preface.indd 4 10/20/2015 3:02:35 PM
http://www.wiley.com/college/koffman
Preface v
Prerequisites Our expectation is that the reader will be familiar with the Java primitive data types including int, boolean, char, and double; control structures including if, case, while, for, and try‐catch; the String class; the one‐dimensional array; input/output using either JOptionPane dialog win- dows or text streams (class Scanner or BufferedReader) and console input/output. For those readers who lack some of the concepts or who need some review, we provide complete coverage of these topics in Appendix A. Although labeled an Appendix, the review chapter provides full coverage of the background topics and has all the pedagogical features (discussed below) of the other chapters. We expect most readers will have some experience with Java programming, but someone who knows another programming language should be able to undertake the book after careful study of the review chapter. We do not require prior knowledge of inheritance, wrapper classes, or ArrayLists as we cover them in the book (Chapters 1 and 2).
Pedagogy The book contains the following pedagogical features to assist inexperienced programmers in learning the material.
• Learning objectives at the beginning of each chapter tell readers what skills they should develop.
• Introductions for each chapter help set the stage for what the chapter will cover and tie the chapter contents to other material that they have learned.
• Case Studies emphasize problem solving and provide complete and detailed solutions to real‐world problems using the data structures studied in the chapter.
• Chapter Summaries review the contents of the chapter. • Boxed Features emphasize and call attention to material designed to help readers become
better programmers.
Pitfall boxes help readers identify common problems and how to avoid them.
Design Concept boxes illuminate programming design decisions and trade‐offs.
Programming Style boxes discuss program features that illustrate good programming style and provide tips for writing clear and effective code.
Syntax boxes are a quick reference for the Java structures being introduced.
• Self‐Check and Programming Exercises at the end of each section provide immediate feedback and practice for readers as they work through the chapter.
• Quick‐Check, Review Exercises, and Programming Projects at the end of each chapter review chapter concepts and give readers a variety of skill‐building activities, including longer projects that integrate chapter concepts as they exercise the use of data structures.
Theoretical Rigor In Chapter 2, we discuss algorithm efficiency and big‐O notation as a measure of algorithm efficiency. We have tried to strike a balance between pure “hand waving” and extreme rigor when determining the efficiency of algorithms. Rather than provide several paragraphs of
Koffman-preface.indd 5 10/20/2015 3:02:42 PM
vi Preface
formulas, we have provided simplified derivations of algorithm efficiency using big‐O nota- tion. We feel this will give readers an appreciation of the performance of various algorithms and methods and the process one follows to determine algorithm efficiency without bogging them down in unnecessary detail.
Overview of the book Chapter 1 introduces Object Oriented Programming, inheritance, and class hierarchies including interfaces and abstract classes. We also introduce UML class diagrams and Javadoc‐ style documentation. The Exception class hierarchy is studied as an example of a Java class hierarchy.
Chapter 2 introduces the Java Collections Framework as the foundation for the traditional data structures. These are covered in separate chapters: lists (Chapter 2), stacks, queues and deques (Chapter 4), Trees (Chapters 6 and 9), Sets and Maps (Chapter 7), and Graphs (Chapter 10). Each new data structure is introduced as an abstract data type (ADT). We pro- vide a specification of each ADT in the form of a Java interface. Next, we implement the data structure as a class that implements the interface. Finally, we study applications of the data structure by solving sample problems and case studies.
Chapter 3 covers different aspects of testing (e.g. top‐down, bottom‐up, white‐box, black‐ box). It includes a section on developing a JUnit test harness and also a section on Test‐ Driven Development. It also discuses using a debugger to help find and correct errors.
Chapter 4 discusses stacks, queues, and deques. Several applications of these data structures are provided.
Chapter 5 covers recursion so that readers are prepared for the study of trees, a recursive data structure. This chapter could be studied earlier. There is an optional section on list processing applications of recursion that may be skipped if the chapter is covered earlier.
Chapter 6 discusses binary trees, including binary search trees, heaps, priority queues, and Huffman trees. It also shows how Java 8 lambda expressions and functional interfaces sup- port functional programming.
Chapter 7 covers the Set and Map interfaces. It also discusses hashing and hash tables and shows how a hash table can be used in an implementation of these interfaces. Building an index for a file and Huffman Tree encoding and decoding are two case studies covered in this chapter.
Chapter 8 covers various sorting algorithms including mergesort, heapsort, quicksort and Timsort.
Chapter 9 covers self‐balancing search trees, focusing on algorithms for manipulating them. Included are AVL and Red‐Black trees, 2‐3 trees, 2‐3‐4 trees, B‐trees, and skip‐lists.
Chapter 10 covers graphs. We provide several well‐known algorithms for graphs, including Dijkstra’s shortest path algorithm and Prim’s minimal spanning tree algorithm. In most pro- grams, the last few chapters would be covered in a second course in algorithms and data structures.
Supplements and Companion Web Sites The following supplementary materials are available on the Instructor’s Companion Web Site for this textbook at www.wiley.com/college/koffman. Items marked for students are accessi- ble on the Student Companion Web Site at the same address.
Koffman-preface.indd 6 10/20/2015 3:02:42 PM
http://www.wiley.com/college/koffman
Preface vii
• Additional homework problems with solutions • Additional case studies, including one that illustrates a solution to the same problem
using several different data structures • Source code for all classes in the book (for students and instructors) • PowerPoint slides • Electronic test bank for instructors • Solutions to end‐of‐section odd‐numbered self‐check and programming exercises (for students) • Solutions to all exercises for instructors • Solutions to chapter‐review exercises for instructors • Sample programming project solutions for instructors • Additional homework and laboratory projects, including cases studies and solutions
Acknowledgments Many individuals helped us with the preparation of this book and improved it greatly. We are grateful to all of them. These include students at Temple University who have used notes that led to the preparation of this book in their coursework, and who class‐tested early drafts of the book. We would like to thank Rolf Lakaemper and James Korsh, colleagues at Temple University, who used earlier editions in their classes. We would also like to thank a former Temple student, Michael Mayle, who provided preliminary solutions to many of the exercises.
We would also like to acknowledge support from the National Science Foundation (grant num- ber DUE‐1225742) and Principal Investigator Peter J. Clarke, Florida International University (FIU), to attend the Fifth Workshop on Integrating Software Testing into Programming Courses (WISTPC 2014) at FIU. Some of the testing methodologies discussed at the workshop were integrated into the chapter on Testing and Debugging.
We are especially grateful to our reviewers who provided invaluable comments that helped us correct errors in each version and helped us set our revision goals for the next version. The individuals who reviewed this book are listed below.
Reviewers Sheikh Iqbal Ahamed, Marquette University Justin Beck, Oklahoma State University John Bowles, University of South Carolina Mary Elaine Califf, Illinois State University Tom Cortina, SUNY Stony Brook Adrienne Decker, SUNY Buffalo Chris Dovolis, University of Minnesota Vladimir Drobot, San Jose State University Kenny Fong, Southern Illinois University, Carbondale Ralph Grayson, Oklahoma State University Allan M. Hart, Minnesota State University, Mankato James K. Huggins, Kettering University Chris Ingram, University of Waterloo Gregory Kesden, Carnegie Mellon University Sarah Matzko, Clemson University Lester McCann, University of Arizona
Koffman-preface.indd 7 10/20/2015 3:02:42 PM
viii Preface
Ron Metoyer, Oregon State University Rich Pattis, Carnegie Mellon University Thaddeus F. Pawlicki, University of Rochester Sally Peterson, University of Wisconsin—Madison Salam N. Salloum, California State Polytechnic University, Pomona Mike Scott, University of Texas—Austin Victor Shtern, Boston University Mark Stehlik, Carnegie Mellon University Ralph Tomlinson, Iowa State University Frank Tompa, University of Waterloo Renee Turban, Arizona State University Paul Tymann, Rochester Institute of Technology Karen Ward, University of Texas—El Paso Jim Weir, Marist College Lee Wittenberg, Kean University Martin Zhao, Mercer University
Although all the reviewers provided invaluable suggestions, we do want to give special thanks to Chris Ingram who reviewed every version of the first edition of the manuscript, including the preliminary pages for the book. His care, attention to detail, and dedication helped us improve this book in many ways, and we are very grateful for his efforts.
Besides the principal reviewers, there were a number of faculty members who reviewed sample pages of the first edition online and made valuable comments and criticisms of its content. We would like to thank those individuals, listed below.
Content Connections Online Review Razvan Andonie, Central Washington University Antonia Boadi, California State University Dominguez Hills Mikhail Brikman, Salem State College Robert Burton, Brigham Young University Chakib Chraibi, Barry University Teresa Cole, Boise State University Jose Cordova, University of Louisiana Monroe Joyce Crowell, Belmont University Robert Franks, Central College Barabra Gannod, Arizona State University East Wayne Goddard, Clemson University Simon Gray, College of Wooster Wei Hu, Houghton College Edward Kovach, Franciscan University of Steubenville Saeed Monemi, California Polytechnic and State University Robert Noonan, College of William and Mary
Koffman-preface.indd 8 10/20/2015 3:02:43 PM
Preface ix
Kathleen O’Brien, Foothill College Rathika Rajaravivarma, Central Connecticut State University Sam Rhoads, Honolulu Community College Vijayakumar Shanmugasundaram, Concordia College Moorhead Gene Sheppard, Perimeter College Linda Sherrell, University of Memphis Meena Srinivasan, Mary Washington College David Weaver, Sheperd University Stephen Weiss, University of North Carolina—Chapel Hill Glenn Wiggins, Mississippi College Bruce William, California State University Pomona
Finally, we want to acknowledge the participants in focus groups for the second programming course organized by John Wiley & Sons at the Annual Meeting of the SIGCSE Symposium in March 2004. They reviewed the preface, table of contents, and sample chapters and also provided valuable input on the book and future directions of the course.
Focus Group Claude Anderson, Rose-Hulman Institute of Technology Jay M. Anderson, Franklin & Marshall University John Avitabile, College of Saint Rose Cathy Bishop‐Clark, Miami University—Middletown Debra Burhans, Canisius College Michael Clancy, University of California—Berkeley Nina Cooper, University of Nevada Las Vegas Kossi Edoh, Montclair State University Robert Franks, Central College Evan Golub, University of Maryland Graciela Gonzalez, Sam Houston State University Scott Grissom, Grand Valley State University Jim Huggins, Kettering University Lester McCann, University of Wisconsin—Parkside Briana Morrison, Southern Polytechnic State University Judy Mullins, University of Missouri—Kansas City Roy Pargas, Clemson University J.P. Pretti, University of Waterloo Reza Sanati, Utah Valley State College Barbara Smith, University of Dayton Suzanne Smith, East Tennessee State University Michael Stiber, University of Washington, Bothell Jorge Vasconcelos, University of Mexico (UNAM) Lee Wittenberg, Kean University
Koffman-preface.indd 9 10/20/2015 3:02:43 PM
x Preface
We would also like to acknowledge and thank the team at John Wiley & Sons who were responsible for the management of this edition and ably assisted us with all phases of the book development and production. They were Gladys Soto, Project Manager, Nichole Urban, Project Specialist, and Rajeshkumar Nallusamy, Production Editor.
We would like to acknowledge the help and support of our colleague Frank Friedman who also read an early draft of this textbook and offered suggestions for improvement. Frank and Elliot began writing textbooks together many years ago and Frank has had substantial influ- ence on the format and content of these books. Frank also influenced Paul to begin his teach- ing career as an adjunct faculty member and then hired him as a full‐time faculty member when he retired from industry. Paul is grateful for his continued support.
Finally, we would like to thank our wives who provided us with comfort and support through this arduous process. We very much appreciate their understanding and their sacrifices that enabled us to focus on this book, often during time we would normally be spending with them. In particular, Elliot Koffman would like to thank
Caryn Koffman
and Paul Wolfgang would like to thank
Sharon Wolfgang
Koffman-preface.indd 10 10/20/2015 3:02:43 PM
Contents xi
Contents Preface iii
Chapter 1 Object-Oriented Programming and Class Hierarchies 1
1.1 ADTs, Interfaces, and the Java API 2 Interfaces 2 The implements Clause 5 Declaring a Variable of an Interface Type 6 Exercises for Section 1.1 6
1.2 Introduction to Object‐Oriented Programming (OOP) 7 A Superclass and Subclass Example 8 Use of this. 9 Initializing Data Fields in a Subclass 10 The No‐Parameter Constructor 11 Protected Visibility for Superclass Data Fields 11 Is‐a versus Has‐a Relationships 12 Exercises for Section 1.2 12
1.3 Method Overriding, Method Overloading, and Polymorphism 13 Method Overriding 13 Method Overloading 15 Polymorphism 17 Methods with Class Parameters 17 Exercises for Section 1.3 18
1.4 Abstract Classes 19 Referencing Actual Objects 21 Initializing Data Fields in an Abstract Class 21 Abstract Class Number and the Java Wrapper Classes 21 Summary of Features of Actual Classes, Abstract Classes, and Interfaces 22 Implementing Multiple Interfaces 23 Extending an Interface 23 Exercises for Section 1.4 23
1.5 Class Object and Casting 24 The Method toString 24 Operations Determined by Type of Reference Variable 25 Casting in a Class Hierarchy 26 Using instanceof to Guard a Casting Operation 27 The Class Class 29 Exercises for Section 1.5 29
1.6 A Java Inheritance Example—The Exception Class Hierarchy 29 Division by Zero 29 Array Index Out of Bounds 30 Null Pointer 31 The Exception Class Hierarchy 31
Koffman-ftoc.indd 11 10/20/2015 3:01:55 PM
xii Contents
The Class Throwable 31 Checked and Unchecked Exceptions 32 Handling Exceptions to Recover from Errors 34 Using try‐catch to Recover from an Error 34 Throwing an Exception When Recovery Is Not Obvious 35 Exercises for Section 1.6 36
1.7 Packages and Visibility 36 Packages 36 The No‐Package‐Declared Environment 37 Package Visibility 38 Visibility Supports Encapsulation 38 Exercises for Section 1.7 39
1.8 A Shape Class Hierarchy 39 Case Study: Processing Geometric Figures 40 Exercises for Section 1.8 45 Java Constructs Introduced in This Chapter 46 Java API Classes Introduced in This Chapter 46 User‐Defined Interfaces and Classes in This Chapter 47 Quick‐Check Exercises 47 Review Questions 47 Programming Projects 48 Answers to Quick-Check Exercises 51
Chapter 2 Lists and the Collections Framework 53
2.1 Algorithm Efficiency and Big-O 54 Big-O Notation 56 Formal Definition of Big-O 57 Summary of Notation 60 Comparing Performance 60 Algorithms with Exponential and Factorial Growth Rates 62 Exercises for Section 2.1 62
2.2 The List Interface and ArrayList Class 63 The ArrayList Class 64 Generic Collections 66 Exercises for Section 2.2 68
2.3 Applications of ArrayList 68 A Phone Directory Application 69 Exercises for Section 2.3 69
2.4 Implementation of an ArrayList Class 70 The Constructor for Class KWArrayList 71 The add(E anEntry) Method 72 The add(int index, E anEntry) Method 73 The set and get Methods 73 The remove Method 74 The reallocate Method 74 Performance of the KWArrayList Algorithms 74 Exercises for Section 2.4 75
2.5 Single‐Linked Lists 75 A List Node 77
Koffman-ftoc.indd 12 10/20/2015 3:01:55 PM
Contents xiii
Connecting Nodes 78 A Single-Linked List Class 79 Inserting a Node in a List 79 Removing a Node 80 Completing the SingleLinkedList Class 81 The get and set Methods 82 The add Methods 82 Exercises for Section 2.5 83
2.6 Double‐Linked Lists and Circular Lists 84 The Node Class 85 Inserting into a Double‐Linked List 86 Removing from a Double‐Linked List 86 A Double‐Linked List Class 86 Circular Lists 87 Exercises for Section 2.6 88
2.7 The LinkedList Class and the Iterator, ListIterator, and Iterable Interfaces 89 The LinkedList Class 89 The Iterator 89 The Iterator Interface 90 The Enhanced for Loop 92 The ListIterator Interface 92 Comparison of Iterator and ListIterator 94 Conversion between a ListIterator and an Index 95 The Iterable Interface 95 Exercises for Section 2.7 95
2.8 Application of the LinkedList Class 96 Case Study: Maintaining an Ordered List 96 Testing Class OrderedList 101 Exercises for Section 2.8 103
2.9 Implementation of a Double‐Linked List Class 103 Implementing the KWLinkedList Methods 104 A Class that Implements the ListIterator Interface 104 The Constructor 105 The hasNext and next Methods 106 The hasPrevious and previous Methods 107 The add Method 107 Inner Classes: Static and Nonstatic 111 Exercises for Section 2.9 111
2.10 The Collections Framework Design 112 The Collection Interface 112 Common Features of Collections 113 The AbstractCollection, AbstractList, and AbstractSequentialList Classes 113 The List and RandomAccess Interfaces (Advanced) 114 Exercises for Section 2.10 114 Java API Interfaces and Classes Introduced in this Chapter 116 User‐Defined Interfaces and Classes in this Chapter 116 Quick‐Check Exercises 116 Review Questions 117 Programming Projects 117 Answers to Quick-Check Exercises 119
Koffman-ftoc.indd 13 10/20/2015 3:01:55 PM
xiv Contents
Chapter 3 Testing and Debugging 121
3.1 Types of Testing 122 Preparations for Testing 124 Testing Tips for Program Systems 124 Exercises for Section 3.1 125
3.2 Specifying the Tests 125 Testing Boundary Conditions 125 Exercises for Section 3.2 126
3.3 Stubs and Drivers 127 Stubs 127 Preconditions and Postconditions 127 Drivers 128 Exercises for Section 3.3 128
3.4 The JUnit Test Framework 128 Exercises for Section 3.4 132
3.5 Test‐Driven Development 132 Exercises for Section 3.5 136
3.6 Testing Interactive Programs in JUnit 137 ByteArrayInputStream 138
ByteArrayOutputStream 138
Exercises for Section 3.6 139
3.7 Debugging a Program 139 Using a Debugger 140 Exercises for Section 3.7 142 Java API Classes Introduced in This Chapter 144 User‐Defined Interfaces and Classes in This Chapter 144 Quick‐Check Exercises 144 Review Questions 144 Programming 144 Answers to Quick-Check Exercises 146
Chapter 4 Stacks and Queues 147
4.1 Stack Abstract Data Type 148 Specification of the Stack Abstract Data Type 148 Exercises for Section 4.1 150
4.2 Stack Applications 151 Case Study: Finding Palindromes 151 Exercises for Section 4.2 155
4.3 Implementing a Stack 155 Implementing a Stack with an ArrayList Component 155 Implementing a Stack as a Linked Data Structure 157 Comparison of Stack Implementations 158 Exercises for Section 4.3 159
4.4 Additional Stack Applications 159 Case Study: Evaluating Postfix Expressions 160 Case Study: Converting From Infix To Postfix 165
Koffman-ftoc.indd 14 10/20/2015 3:01:55 PM
Contents xv
Case Study: Converting Expressions with Parentheses 173 Tying the Case Studies Together 176 Exercises for Section 4.4 176
4.5 Queue Abstract Data Type 177 A Print Queue 177 The Unsuitability of a “Print Stack” 178 A Queue of Customers 178 Using a Queue for Traversing a Multi‐Branch Data Structure 178 Specification for a Queue Interface 179 Class LinkedList Implements the Queue Interface 179 Exercises for Section 4.5 180
4.6 Queue Applications 181 Case Study: Maintaining a Queue 181 Exercises for Section 4.6 186
4.7 Implementing the Queue Interface 187 Using a Double‐Linked List to Implement the Queue Interface 187 Using a Single‐Linked List to Implement the Queue Interface 187 Using a Circular Array to Implement the Queue Interface 189 Exercises for Section 4.7 196
4.8 The Deque Interface 196 Classes that Implement Deque 198 Using a Deque as a Queue 198 Using a Deque as a Stack 198 Exercises for Section 4.8 199 Java API Classes Introduced in This Chapter 200 User‐Defined Interfaces and Classes in This Chapter 200 Quick‐Check Exercises 201 Review Questions 202 Programming Projects 203 Answers to Quick-Check Exercises 207
Chapter 5 Recursion 211
5.1 Recursive Thinking 212 Steps to Design a Recursive Algorithm 214 Proving that a Recursive Method Is Correct 216 Tracing a Recursive Method 216 The Run‐Time Stack and Activation Frames 217 Exercises for Section 5.1 218
5.2 Recursive Definitions of Mathematical Formulas 219 Tail Recursion versus Iteration 222 Efficiency of Recursion 223 Exercises for Section 5.2 225
5.3 Recursive Array Search 226 Design of a Recursive Linear Search Algorithm 226 Implementation of Linear Search 227 Design of a Binary Search Algorithm 228 Efficiency of Binary Search 229 The Comparable Interface 230
Koffman-ftoc.indd 15 10/20/2015 3:01:55 PM
xvi Contents
Implementation of Binary Search 230 Testing Binary Search 232 Method Arrays.binarySearch 233 Exercises for Section 5.3 233
5.4 Recursive Data Structures 233 Recursive Definition of a Linked List 234 Class LinkedListRec 234 Removing a List Node 236 Exercises for Section 5.4 237
5.5 Problem Solving with Recursion 238 Case Study: Towers of Hanoi 238 Case Study: Counting Cells in a Blob 243 Exercises for Section 5.5 247
5.6 Backtracking 247 Case Study: Finding a Path through a Maze 248 Exercises for Section 5.6 252 User‐Defined Classes in This Chapter 253 Quick‐Check Exercises 253 Review Questions 253 Programming Projects 254 Answers to Quick-Check Exercises 255
Chapter 6 Trees 257
6.1 Tree Terminology and Applications 258 Tree Terminology 258 Binary Trees 259 Some Types of Binary Trees 260 Full, Perfect, and Complete Binary Trees 263 General Trees 263 Exercises for Section 6.1 264
6.2 Tree Traversals 265 Visualizing Tree Traversals 266 Traversals of Binary Search Trees and Expression Trees 266 Exercises for Section 6.2 267
6.3 Implementing a BinaryTree Class 268 The Node Class 268 The BinaryTree Class 269 Exercises for Section 6.3 275
6.4 Java 8 Lambda Expressions and Functional Interfaces 276 Functional Interfaces 277 Passing a Lambda Expression as an Argument 279 A General Preorder Traversal Method 280 Using preOrderTraverse 280 Exercises for Section 6.4 281
6.5 Binary Search Trees 282 Overview of a Binary Search Tree 282 Performance 283
Koffman-ftoc.indd 16 10/20/2015 3:01:55 PM
Contents xvii
Interface SearchTree 283 The BinarySearchTree Class 283 Insertion into a Binary Search Tree 285 Removal from a Binary Search Tree 288 Testing a Binary Search Tree 293 Case Study: Writing an Index for a Term Paper 294 Exercises for Section 6.5 297
6.6 Heaps and Priority Queues 297 Inserting an Item into a Heap 298 Removing an Item from a Heap 298 Implementing a Heap 299 Priority Queues 302 The PriorityQueue Class 303 Using a Heap as the Basis of a Priority Queue 303 The Other Methods 306 Using a Comparator 306 The compare Method 306 Exercises for Section 6.6 307
6.7 Huffman Trees 308 Case Study: Building a Custom Huffman Tree 310 Exercises for Section 6.6 315 Java API Interfaces and Classes Introduced in This Chapter 316 User‐Defined Interfaces and Classes in This Chapter 317 Quick‐Check Exercises 317 Review Questions 318 Programming Projects 318 Answers to Quick-Check Exercises 320
Chapter 7 Sets and Maps 323
7.1 Sets and the Set Interface 324 The Set Abstraction 324 The Set Interface and Methods 325 Comparison of Lists and Sets 327 Exercises for Section 7.1 328
7.2 Maps and the Map Interface 329 The Map Hierarchy 330 The Map Interface 330 Exercises for Section 7.2 332
7.3 Hash Tables 333 Hash Codes and Index Calculation 333 Methods for Generating Hash Codes 334 Open Addressing 335 Table Wraparound and Search Termination 335 Traversing a Hash Table 337 Deleting an Item Using Open Addressing 337 Reducing Collisions by Expanding the Table Size 338 Reducing Collisions Using Quadratic Probing 338 Problems with Quadratic Probing 339
Koffman-ftoc.indd 17 10/20/2015 3:01:55 PM
xviii Contents
Chaining 340 Performance of Hash Tables 340 Exercises for Section 7.3 342
7.4 Implementing the Hash Table 344 Interface KWHashMap 344 Class Entry 344 Class HashtableOpen 345 Class HashtableChain 350 Testing the Hash Table Implementations 353 Exercises for Section 7.4 354
7.5 Implementation Considerations for Maps and Sets 354 Methods hashCode and equals 354 Implementing HashSetOpen 355 Writing HashSetOpen as an Adapter Class 355 Implementing the Java Map and Set Interfaces 356 Interface Map.Entry and Class AbstractMap.SimpleEntry 356 Creating a Set View of a Map 357 Method entrySet and Classes EntrySet and SetIterator 357 Classes TreeMap and TreeSet 358 Exercises for Section 7.5 359
7.6 Additional Applications of Maps 359 Case Study: Implementing a Cell Phone Contact List 359 Case Study: Completing the Huffman Coding Problem 361 Encoding the Huffman Tree 365 Exercises for Section 7.6 366
7.7 Navigable Sets and Maps 366 Application of a NavigableMap 368 Exercises for Section 7.7 370 Java API Interfaces and Classes Introduced in This Chapter 372 User‐Defined Interfaces and Classes in This Chapter 372 Quick‐Check Exercises 372 Review Questions 372 Programming Projects 373 Answers to Quick-Check Exercises 374
Chapter 8 Sorting 375
8.1 Using Java Sorting Methods 376 Exercises for Section 8.1 380
8.2 Selection Sort 380 Analysis of Selection Sort 381 Code for Selection Sort 381 Exercises for Section 8.2 383
8.3 Insertion Sort 383 Analysis of Insertion Sort 384 Code for Insertion Sort 385 Exercises for Section 8.3 386
8.4 Comparison of Quadratic Sorts 386 Comparisons versus Exchanges 387 Exercises for Section 8.4 388
Koffman-ftoc.indd 18 10/20/2015 3:01:55 PM
Contents xix
8.5 Shell Sort: A Better Insertion Sort 388 Analysis of Shell Sort 389 Code for Shell Sort 390 Exercises for Section 8.5 391
8.6 Merge Sort 391 Analysis of Merge 392 Code for Merge 392 Algorithm for Merge Sort 394 Trace of Merge Sort Algorithm 394 Analysis of Merge Sort 394 Code for Merge Sort 395 Exercises for Section 8.6 396
8.7 Timsort 397 Merging Adjacent Sequences 400 Implementation 400
8.8 Heapsort 405 First Version of a Heapsort Algorithm 405 Revising the Heapsort Algorithm 405 Algorithm to Build a Heap 407 Analysis of Revised Heapsort Algorithm 407 Code for Heapsort 407 Exercises for Section 8.8 409
8.9 Quicksort 409 Algorithm for Quicksort 410 Analysis of Quicksort 411 Code for Quicksort 411 Algorithm for Partitioning 412 Code for partition 413 A Revised partition Algorithm 415 Code for Revised partition Method 416 Exercises for Section 8.9 417
8.10 Testing the Sort Algorithms 417 Exercises for Section 8.10 419
8.11 The Dutch National Flag Problem (Optional Topic) 419 Case Study: The Problem of the Dutch National Flag 419 Exercises for Section 8.11 422 Java Classes Introduced in This Chapter 423 User‐Defined Interfaces and Classes in This Chapter 423 Quick‐Check Exercises 424 Review Questions 424 Programming Projects 424 Answers to Quick-Check Exercises 425
Chapter 9 Self-Balancing Search Trees 427
9.1 Tree Balance and Rotation 428 Why Balance Is Important 428 Rotation 428 Algorithm for Rotation 429 Implementing Rotation 430 Exercises for Section 9.1 432
Koffman-ftoc.indd 19 10/20/2015 3:01:55 PM
xx Contents
9.2 AVL Trees 432 Balancing a Left–Left Tree 432 Balancing a Left–Right Tree 433 Four Kinds of Critically Unbalanced Trees 434 Implementing an AVL Tree 436 Inserting into an AVL Tree 438 Removal from an AVL Tree 443 Performance of the AVL Tree 444 Exercises for Section 9.2 444
9.3 Red–Black Trees 445 Insertion into a Red–Black Tree 445 Removal from a Red–Black Tree 455 Performance of a Red–Black Tree 455 The TreeMap and TreeSet Classes 455 Exercises for Section 9.3 456
9.4 2–3 Trees 456 Searching a 2–3 Tree 457 Inserting an Item into a 2–3 Tree 457 Analysis of 2–3 Trees and Comparison with Balanced Binary Trees 461 Removal from a 2–3 Tree 461 Exercises for Section 9.4 462
9.5 B‐Trees and 2–3–4 Trees 463 B‐Trees 463 Implementing the B‐Tree 464 Code for the insert Method 466 The insertIntoNode Method 467 The splitNode Method 468 Removal from a B‐Tree 470 B+ Trees 471 2–3–4 Trees 471 Relating 2–3–4 Trees to Red–Black Trees 473 Exercises for Section 9.5 474
9.6 Skip‐Lists 475 Skip‐List Structure 475 Searching a Skip‐List 476 Performance of a Skip‐List Search 477 Inserting into a Skip‐List 477 Increasing the Height of a Skip‐List 477 Implementing a Skip‐List 477 Searching a Skip‐List 478 Insertion 479 Determining the Size of the Inserted Node 480 Completing the Insertion Process 480 Performance of a Skip‐List 480 Exercises for Section 9.6 480 Java Classes Introduced in This Chapter 482 User‐Defined Interfaces and Classes in This Chapter 482 Quick‐Check Exercises 482
Koffman-ftoc.indd 20 10/20/2015 3:01:55 PM
Contents xxi
Review Questions 483 Programming Projects 484 Answers to Quick-Check Exercises 486
Chapter 10 Graphs 489
10.1 Graph Terminology 490 Visual Representation of Graphs 490 Directed and Undirected Graphs 491 Paths and Cycles 491 Relationship between Graphs and Trees 493 Graph Applications 493 Exercises for Section 10.1 494
10.2 The Graph ADT and Edge Class 494 Representing Vertices and Edges 495 Exercises for Section 10.2 496
10.3 Implementing the Graph ADT 496 Adjacency List 497 Adjacency Matrix 497 Overview of the Hierarchy 499 Class AbstractGraph 499 The ListGraph Class 501 The MatrixGraph Class 503 Comparing Implementations 504 The MapGraph Class 505 Exercises for Section 10.3 505
10.4 Traversals of Graphs 506 Breadth‐First Search 506 Algorithm for Breadth‐First Search 508 Depth‐First Search 511 Exercises for Section 10.4 517
10.5 Applications of Graph Traversals 517 Case Study: Shortest Path through a Maze 517 Case Study: Topological Sort of a Graph 521 Exercises for Section 10.5 524
10.6 Algorithms Using Weighted Graphs 524 Finding the Shortest Path from a Vertex to All Other Vertices 524 Minimum Spanning Trees 528 Exercises for Section 10.6 531 User‐Defined Classes and Interfaces in This Chapter 533 Quick‐Check Exercises 533 Review Questions 534 Programming Projects 534 Answers to Quick-Check Exercises 536
Appendix A Introduction to Java 541
A.1 The Java Environment and Classes 542 The Java Virtual Machine 543
Koffman-ftoc.indd 21 10/20/2015 3:01:55 PM
xxii Contents
The Java Compiler 543 Classes and Objects 543 The Java API 543 The import Statement 544 Method main 544 Execution of a Java Program 545 Exercises for Section A.1 545
A.2 Primitive Data Types and Reference Variables 545 Primitive Data Types 545 Primitive‐Type Variables 547 Primitive‐Type Constants 547 Operators 547 Postfix and Prefix Increment 549 Type Compatibility and Conversion 549 Referencing Objects 550 Creating Objects 550 Exercises for Section A.2 551
A.3 Java Control Statements 551 Sequence and Compound Statements 551 Selection and Repetition Control 551 Nested if Statements 553 The switch Statement 555 Exercises for Section A.3 555
A.4 Methods and Class Math 555 The Instance Methods println and print 556 Call‐by‐Value Arguments 557 The Class Math 557 Escape Sequences 558 Exercises for Section A.4 559
A.5 The String, StringBuilder, StringBuffer, and StringJoiner Classes 559 The String Class 559 Strings Are Immutable 562 The Garbage Collector 562 Comparing Objects 562 The String.format Method 564 The Formatter Class 565 The String.split Method 565 Introduction to Regular Expressions 565 Matching One of a Group of Characters 566 Qualifiers 566 Defined Character Groups 567 Unicode Character Class Support 567 The StringBuilder and StringBuffer Classes 567 Java 8 StringJoiner Class 569 Exercises for Section A.5 570
A.6 Wrapper Classes for Primitive Types 571 Exercises for Section A.6 572
A.7 Defining Your Own Classes 573 Private Data Fields, Public Methods 576
Koffman-ftoc.indd 22 10/20/2015 3:01:56 PM
Contents xxiii
Constructors 577 The No‐Parameter Constructor 577 Modifier and Accessor Methods 578 Use of this. in a Method 578 The Method toString 578 The Method equals 579 Declaring Local Variables in Class Person 580 An Application that Uses Class Person 580 Objects as Arguments 581 Classes as Components of Other Classes 582 Java Documentation Style for Classes and Methods 582 Exercises for Section A.7 585
A.8 Arrays 585 Data Field length 587 Method Arrays.copyOf 588 Method System.arrayCopy 588 Array Data Fields 589 Array Results and Arguments 590 Arrays of Arrays 590 Exercises for Section A.8 593
A.9 Enumeration Types 594 Using Enumeration Types 595 Assigning Values to Enumeration Types 596 Exercises for Section A.9 596
A.10 I/O Using Streams, Class Scanner, and Class JOptionPane 596 The Scanner 597 Using a Scanner to Read from a File 599 Exceptions 599 Tokenized Input 599 Extracting Tokens Using Scanner.findInLine 600 Using a BufferedReader to Read from an Input Stream 600 Output Streams 600 Passing Arguments to Method main 600 Closing Streams 601 Try with Resources 601 A Complete File‐Processing Application 601 Class InputStream and Character Codes (Optional) 603 The Default Character Coding (Optional) 603 UTF‐8 (Optional) 604 Specifying a Character Encoding (Optional) 605 Input/Output Using Class JOptionPane 605 Converting Numeric Strings to Numbers 606 GUI Menus Using Method showOptionDialog 607 Exercises for Section A.10 607
A.11 Catching Exceptions 608 Catching and Handling Exceptions 608 Exercises for Section A.11 614
A.12 Throwing Exceptions 614 The throws Clause 615
Koffman-ftoc.indd 23 10/20/2015 3:01:56 PM
xxiv Contents
The throw Statement 616 Exercises for Section A.12 619 Java Constructs Introduced in This Appendix 621 Java API Classes Introduced in This Appendix 622 User‐Defined Interfaces and Classes in This Appendix 622 Quick‐Check Exercises 622 Review Questions 622 Programming Projects 623 Answer to Quick‐Check Exercises 624
Appendix B Overview of UML 625
B.1 The Class Diagram 626 Representing Classes and Interfaces 626 Generalization 629 Inner or Nested Classes 629 Association 629 Aggregation and Composition 630 Generic Classes 631
B.2 Sequence Diagrams 631 Time Axis 632 Objects 633 Life Lines 633 Activation Bars 633 Messages 633 Use of Notes 633
Glossary 635 Index 643
Koffman-ftoc.indd 24 10/20/2015 3:01:56 PM
C h a p t e r
1
This chapter describes important features of Java that support Object‐Oriented Programming (OOP). Object‐oriented languages allow you to build and exploit hierarchies of classes in order to write code that may be more easily reused in new applications. You will learn how to extend an existing Java class to define a new class that inherits all the attributes of the original, as well as having additional attributes of its own. Because there may be many versions of the same method in a class hierarchy, we show how polymorphism enables Java to determine which version to execute at any given time.
We introduce interfaces and abstract classes and describe their relationship with each other and with actual classes. We introduce the abstract class Number. We also discuss class Object, which all classes extend, and we describe several of its methods that may be used in classes you create.
As an example of a class hierarchy and OOP, we describe the Exception class hierarchy and explain that the Java Virtual Machine (JVM) creates an Exception object whenever an error occurs during program execution. Finally, you will learn how to create packages in Java and about the different kinds of visibility for instance variables (data fields) and methods.
Object‐Oriented Programming and Class Hierarchies
1C h a p t e r
C h a p t e r O b j e c t i v e s
◆ To learn about interfaces and their role in Java ◆ To understand inheritance and how it facilitates code reuse ◆ To understand how Java determines which method to execute when there are multiple methods with the same name in a class hierarchy
◆ To become familiar with the Exception hierarchy and the difference between checked and unchecked exceptions
◆ To learn how to define and use abstract classes as base classes in a hierarchy ◆ To learn the role of abstract data types and how to specify them using interfaces ◆ To study class Object and its methods and to learn how to override them ◆ To become familiar with a class hierarchy for shapes ◆ To understand how to create packages and to learn more about visibility
Koffman-c01.indd 1 10/30/2015 7:39:45 PM
2 Chapter 1 Object‐Oriented Programming and Class Hierarchies
1.1 ADTs, Interfaces, and the Java API
In earlier programming courses, you learned how to write individual classes consisting of attributes and methods (operations). You also learned how to use existing classes (e.g., String and Scanner) to facilitate your programming. These classes are part of the Java Application Programming Interface (API).
One of our goals is to write code that can be reused in many different applications. One way to make code reusable is to encapsulate the data elements together with the methods that operate on that data. A new program can then use the methods to manipulate an object’s data without being concerned about details of the data representation or the method implementa- tions. The encapsulated data together with its methods is called an abstract data type (ADT).
Figure 1.1 shows a diagram of an ADT. The data values stored in the ADT are hidden inside the circular wall. The bricks around this wall are used to indicate that these data values can- not be accessed except by going through the ADT’s methods.
A class provides one way to implement an ADT in Java. If the data fields are private, they can be accessed only through public methods. Therefore, the methods control access to the data and determine the manner in which the data is manipulated.
Another goal of this text is to show you how to write and use ADTs in programming. As you progress through this book, you will create a large collection of ADT implementations (classes) in your own program library. You will also learn about ADTs that are available for you to use through the Java API.
Our principal focus will be on ADTs that are used for structuring data to enable you to more easily and efficiently store, organize, and process information. These ADTs are often called data structures. We introduce the Java Collections Framework (part of the Java API), which provides implementation of these common data structures, in Chapter 2 and study it through- out the text. Using the classes that are in the Java Collections Framework will make it much easier for you to design and implement new application programs.
Interfaces A Java interface is a way to specify or describe an ADT to an applications programmer. An interface is like a contract that tells the applications programmer precisely what methods are available and describes the operations they perform. It also tells the applications programmer
I n h e r i t a n c e a n d C l a s s H i e r a r c h i e s
1.1 ADTs, Interfaces, and the Java API 1.2 Introduction to Object‐Oriented Programming 1.3 Method Overriding, Method Overloading, and Polymorphism 1.4 Abstract Classes 1.5 Class Object and Casting 1.6 A Java Inheritance Example—The Exception Class Hierarchy 1.7 Packages and Visibility 1.8 A Shape Class Hierarchy