Reserved Words Reserved words are also called keywords. You may not redefine any of these reserved words. Their meanings are determined by the Java language and cannot be changed. In particular, you cannot use any of these reserved words for variable names, method names, or class names. abstract false package void assert final private volatile finally protected boolean float public while break for byte return goto case short catch if static char implements strictfp class import super const instanceof switch continue int synchronized interface default this do long throw double throws native transient else new true enum null try extends This page intentionally left blank Operator Precedence In the following list, operators on the same line are of equal precedence. As you move down the list, each line is of lower precedence. When the order of operations is not dictated by parenthe- ses, the operator of higher precedence executes before an operator of lower precedence. When operators have equal precedence, binary operators execute in left-to-right order, and unary oper- ators execute in right-to-left order. Highest Precedence The unary operators +, -, ++, --, !, ~ The unary operators new and (type) The binary operators *, /, % The binary operators +, - The binary (shift) operators <<, >>, >>> The binary operators <, >, <=, >= The binary operators ==, != The binary operator & The binary operator ^ The binary operator | The binary operator && The binary operator || The ternary (conditional) operator ? : Assignment operators =, *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |= Lowest Precedence Primitive Data Types Type Size Values Integer byte 1 byte -128 to 127 short 2 bytes -32,768 to 32,767 int 4 bytes -2,147,483,648 to 2,147,483,647 long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Real float 4 bytes -3.402824 x 1038 to 3.402824 x 1038 double 8 bytes -1.79769313486232 x 10308 to 1.79769313486232 x 10308 Character (Unicode) char 2 bytes All Unicode values between 0 and 65,535 Boolean boolean 1 bit true, false Unicode Character Codes The printable characters shown are a subset of the Unicode character set known as the ASCII character set. The numbering is the same whether the characters are considered to be members of the Unicode character set or members of the ASCII character set. (Character number 32 is the blank.) 32 56 8 80 P 104 h 33 ! 57 9 81 Q 105 i 34 " 58 : 82 R 106 j 35 # 59 ; 83 S 107 k 36 $ 60 < 84 T 108 l 37 % 61 = 85 U 109 m 38 & 62 > 86 V 110 n 39 ' 63 ? 87 W 111 o 40 ( 64 @ 88 X 112 p 41 ) 65 A 89 Y 113 q 42 * 66 B 90 Z 114 r 43 + 67 C 91 [ 115 s 44 , 68 D 92 \ 116 t 45 - 69 E 93 ] 117 u 46 . 70 F 94 ^ 118 v 47 / 71 G 95 _ 119 w 48 0 72 H 96 ‘ 120 x 49 1 73 I 97 a 121 y 50 2 74 J 98 b 122 z 51 3 75 K 99 c 123 { 52 4 76 L 100 d 124 | 53 5 77 M 101 e 125 } 54 6 78 N 102 f 126 ~ 55 7 79 O 103 g Data Structures and Abstractions with Java ™ Third Edition \ Frank M. Carrano University of Rhode Island 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 Editorial Director: Marcia Horton Cover Designer: Anthony Gemmellaro Editor in Chief: Michael Hirsch Photo Researcher: AV Manager, Rights and Acquisitions Editor: Tracy Dunkelberger Permissions: Karen Sanatar Editorial Assistant: Stephanie Sellinger Cover Image Credit: © Color Symphony/ Director of Marketing: Patrice Jones Shutterstock Marketing Manager: Yezan Alayan Media Editor: Dan Sandin Marketing Coordinator: Kathryn Ferranti Full-Service Project Management: GEX Vice President, Production: Vince O’Brien Publishing Services Managing Editor: Jeff Holcomb Composition: GEX Publishing Services Associate Managing Editor: Robert Engelhardt Printer/Binder: Edwards Brothers Manufacturing Manager: Nick Sklitsis Cover Printer: Lehigh-Phoenix Color, Hagerstown Operations Specialist: Lisa McDowell Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on the appropriate page within text. Java is a trademark of the Oracle Corporation, 500 Oracle Parkway, Redwood Shores, CA 94065. Copyright © 2012, 2007 and 2003 by Pearson Education, Inc., publishing as Prentice Hall. All rights reserved. Manufactured in the United States of America. This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to 201-236-3290. Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps. Library of Congress Cataloging-in-Publication Data Carrano, Frank M. Data structures and abstractions with Java / Frank M. Carrano. -- 3rd ed. p. cm. Includes bibliographical references and index. ISBN-13: 978-0-13-610091-1 (alk. paper) ISBN-10: 0-13-610091-0 (alk. paper) 1. Data structures (Computer science) 2. Java (Computer program language) I. Title. QA76.9.D33C37 2012 005.13'3--dc23 2011029581 10 9 8 7 6 5 4 3 2 1 ISBN-10: 0-13-610091-0 ISBN-13: 978-0-13-610091-1 W elcome to the third edition of Data Structures and Abstractions with Java, a book for an introductory r course in data structures, typically known as CS-2. Readers of my book Imagine! Java can consider this one o as a sequel. h I wrote this book with you in mind—whether you are an instructor or a student—based upon my experi- t ences during more than three decades of teaching undergraduate computer science. I wanted my book to be u reader friendly so that students could learn more easily and instructors could teach more effectively. To this end, A you will find the material covered in small pieces—I call them “segments”—that are easy to digest and facilitate learning. Numerous examples that mimic real-world situations provide a context for the new material and help to e make it easier for students to learn and retain abstract concepts. Many simple figures illustrate and clarify com- h plicated ideas. Included are over 60 video tutorials to supplement the instruction and help students when their instructor is unavailable. t I hope that you enjoy reading this book. Like many others before you, you can learn—or teach—data m structures in an effective and sustainable way. o Warm regards, r Frank M. Carrano F P. S. I am always available to connect with instructors and students who use my books. Here are a few ways you can reach me: Find me on Facebook: www.facebook.com/makingitreal Follow me on Twitter: twitter.com/Frank_M_Carrano Send me an e-mail: [email protected] Post on my blog: frank-m-carrano.com/makingitreal iii T s he topics that we cover in this book deal with the various ways of organizing data so that a given appli- t cation can access and manipulate data in an efficient way. These topics are fundamental to your future n study of computer science, as they provide you with the foundation of knowledge required to create com- e plex and reliable software. Whether you are interested in designing video games or software for robotic- d controlled surgery, the study of data structures is vital to your success. Even if you do not study all of the topics in this book now, you are likely to encounter them later. I hope that you will enjoy reading the book, u and that it will serve as a useful reference tool for your future courses. t After looking over this preface, you should read the Introduction. There you will quickly see what this S book is about and what you need to know about Java before you begin. Appendices A through G review Java o basics, classes, inheritance, exceptions, files, and javadoc comments. Note that inside the front and back cov- ers you will find Java’s reserved words, its primitive data types, the precedence of its operators, and a list of t Unicode characters. e Please be sure to browse the rest of this preface to see the features that will help you in your studies. t o N A iv (cid:132)Organization and Structure s t T n his book’s organization, sequencing, and pace of topic coverage make learning and teaching easier by e focusing your attention on one concept at a time, by providing flexibility in the order in which you can t cover topics, and by clearly distinguishing between the specification and implementation of abstract data n types, or ADTs. To accomplish these goals, I have organized the material into 30 chapters, composed of small, numbered segments that deal with one concept at a time. Each chapter focuses on either the specifi- o cation and use of an ADT or its various implementations. You can choose to cover the specification of an C ADT followed by its implementations, or you can treat the specification and use of several ADTs before you consider any implementation issues. The book’s organization makes it easy for you to choose the topic f order that you prefer. o e (cid:132)Table of Contents at a Glance l b T he following list of chapter titles shows the overall composition of the book. A further chapter-by-chapter a description appears later. Note that highlighted sections are available online. T Introduction 21. Introducing Hashing f 1. Bags 22. Hashing as a Dictionary Implementation e i 2. Bag Implementations That Use Arrays 23. Trees r 3. A Bag Implementation That Links Data 24. Tree Implementations B 4. The Efficiency of Algorithms 25. A Binary Search Tree Implementation 5. Stacks 26. A Heap Implementation 6. Stack Implementations 27. Balanced Search Trees 7. Recursion 28. Graphs 8. An Introduction to Sorting 29. Graph Implementations 9. Faster Sorting Methods 30. Mutable, Immutable, and Cloneable Objects 10. Queues, Deques, and Priority Queues 11. Queue, Deque, and Priority Queue Implementations Appendices 12. Lists A. Java Essentials 13. List Implementations That Use Arrays B. Java Classes 14. A List Implementation That Links Data C. Creating Classes from Other Classes 15. Iterators D. Designing Classes 16. Sorted Lists E. Handling Exceptions 17. Inheritance and Lists F. File Input and Output 18. Searching G. Documentation and Programming Style 19. Dictionaries Glossary 20. Dictionary Implementations Index v