Maurice Naftalin, Philip Wadler — «Java Generics and Collections

Maurice Naftalin, Philip Wadler — «Java Generics and Collections

Java Generics and Collections Maurice Naftalin and Philip Wadler Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo Java Generics and Collections by Maurice Naftalin and Philip Wadler Copyright © 2007 O’Reilly Media . All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safari.oreilly.com). For more information, contact our corporate/ institutional sales department: (800) 998-9938 or [email protected]. Editor: Mike Loukides Indexers: Maurice Naftalin and Philip Wadler Production Services: Windfall Software Cover Designer: Karen Montgomery Printing History: October 2006: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Java Generics and Collections, the image of an alligator, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. TM This book uses RepKover™, a durable and flexible lay-flat binding. ISBN: 978-0-596-52775-4 [M] [2/09] 1233352047 We dedicate this book to Joyce Naftalin, Lionel Naftalin, Adam Wadler, and Leora Wadler —Maurice Naftalin and Philip Wadler Table of Contents Preface . xi Part I. Generics 1. Introduction . 3 1.1 Generics 4 1.2 Boxing and Unboxing 6 1.3 Foreach 9 1.4 Generic Methods and Varargs 10 1.5 Assertions 12 2. Subtyping and Wildcards . 15 2.1 Subtyping and the Substitution Principle 15 2.2 Wildcards with extends 17 2.3 Wildcards with super 18 2.4 The Get and Put Principle 19 2.5 Arrays 22 2.6 Wildcards Versus Type Parameters 25 2.7 Wildcard Capture 27 2.8 Restrictions on Wildcards 28 3. Comparison and Bounds . 31 3.1 Comparable 31 3.2 Maximum of a Collection 34 3.3 A Fruity Example 36 3.4 Comparator 37 3.5 Enumerated Types 42 3.6 Multiple Bounds 45 3.7 Bridges 47 3.8 Covariant Overriding 49 v 4. Declarations . 51 4.1 Constructors 51 4.2 Static Members 52 4.3 Nested Classes 53 4.4 How Erasure Works 55 5. Evolution, Not Revolution . 59 5.1 Legacy Library with Legacy Client 60 5.2 Generic Library with Generic Client 60 5.3 Generic Library with Legacy Client 62 5.4 Legacy Library with Generic Client 65 5.4.1 Evolving a Library using Minimal Changes 65 5.4.2 Evolving a Library using Stubs 68 5.4.3 Evolving a Library using Wrappers 68 5.5 Conclusions 71 6. Reification . 73 6.1 Reifiable Types 73 6.2 Instance Tests and Casts 74 6.3 Exception Handling 79 6.4 Array Creation 80 6.5 The Principle of Truth in Advertising 82 6.6 The Principle of Indecent Exposure 86 6.7 How to Define ArrayList 89 6.8 Array Creation and Varargs 90 6.9 Arrays as a Deprecated Type? 92 6.10 Summing Up 95 7. Reflection . 97 7.1 Generics for Reflection 97 7.2 Reflected Types are Reifiable Types 100 7.3 Reflection for Primitive Types 101 7.4 A Generic Reflection Library 101 7.5 Reflection for Generics 104 7.6 Reflecting Generic Types 105 8. Effective Generics . 109 8.1 Take Care when Calling Legacy Code 109 8.2 Use Checked Collections to Enforce Security 111 8.3 Specialize to Create Reifiable Types 112 8.4 Maintain Binary Compatibility 117 vi | Table of Contents 9. Design Patterns . 123 9.1 Visitor 123 9.2 Interpreter 127 9.3 Function 128 9.4 Strategy 131 9.5 Subject-Observer 136 Part II. Collections 10. The Main Interfaces of the Java Collections Framework . 145 11. Preliminaries . 147 11.1 Iterable and Iterators 147 11.2 Implementations 149 11.3 Efficiency and the O-Notation 150 11.4 Contracts 152 11.5 Collections and Thread Safety 153 11.5.1 Synchronization and the Legacy Collections 155 11.5.2 JDK 1.2: Synchronized Collections and Fail-Fast Iterators 156 11.5.3 Concurrent Collections: Java 5 and Beyond 158 12. The Collection Interface . 161 12.1 Using the Methods of Collection 164 12.2 Implementing Collection 169 12.3 Collection Constructors 169 13. Sets . 171 13.1 Implementing Set 171 13.1.1 HashSet 172 13.1.2 LinkedHashSet 174 13.1.3 CopyOnWriteArraySet 175 13.1.4 EnumSet 176 13.2 SortedSet and NavigableSet 178 13.2.1 NavigableSet 181 13.2.2 TreeSet 184 13.2.3 ConcurrentSkipListSet 186 13.3 Comparing Set Implementations 188 14. Queues . 191 14.1 Using the Methods of Queue 193 14.2 Implementing Queue 195 14.2.1 PriorityQueue 195 Table of Contents | vii 14.2.2 ConcurrentLinkedQueue 197 14.3 BlockingQueue 198 14.3.1 Using the Methods of BlockingQueue 199 14.3.2 Implementing BlockingQueue 202 14.4 Deque 206 14.4.1 Implementing Deque 208 14.4.2 BlockingDeque 209 14.5 Comparing Queue Implementations 210 15. Lists . 213 15.1 Using the Methods of List 215 15.2 Implementing List 218 15.2.1 ArrayList 218 15.2.2 LinkedList 221 15.2.3 CopyOnWriteArrayList 221 15.3 Comparing List Implementations 221 16. Maps . 223 16.1 Using the Methods of Map 225 16.2 Implementing Map 226 16.2.1 HashMap 227 16.2.2 LinkedHashMap 227 16.2.3 WeakHashMap 229 16.2.4 IdentityHashMap 231 16.2.5 EnumMap 233 16.3 SortedMap and NavigableMap 234 16.3.1 NavigableMap 235 16.3.2 TreeMap 236 16.4 ConcurrentMap 237 16.4.1 ConcurrentHashMap 238 16.5 ConcurrentNavigableMap 238 16.5.1 ConcurrentSkipListMap 239 16.6 Comparing Map Implementations 239 17. The Collections Class . 241 17.1 Generic Algorithms 241 17.1.1 Changing the Order of List Elements 241 17.1.2 Changing the Contents of a List 242 17.1.3 Finding Extreme Values in a Collection 243 17.1.4 Finding Specific Values in a List 243 17.2 Collection Factories 244 17.3 Wrappers 245 17.3.1 Synchronized Collections 245 viii | Table of Contents 17.3.2 Unmodifiable Collections 246 17.3.3 Checked Collections 246 17.4 Other Methods 247 Index . 251 Table of Contents | ix Preface Java now supports generics, the most significant change to the language since the ad- dition of inner classes in Java 1.2—some would say the most significant change to the language ever. Say you wish to process lists. Some may be lists of integers, others lists of strings, and yet others lists of lists of strings. In Java before generics this is simple. You can represent all three by the same class, called List, which has elements of class Object: list of integers List list of strings List list of lists of strings List In order to keep the language simple, you are forced to do some of the work yourself: you must keep track of the fact that you have a list of integers (or strings or lists of strings), and when you extract an element from the list you must cast it from Object back to Integer (or String or List). For instance, the Collections Framework before generics made extensive use of this idiom. Einstein is reputed to have said, “Everything should be as simple as possible but no simpler”. And some might say the approach above is too simple. In Java with generics you may distinguish different types of lists: list of integers List<Integer> list of strings List<String> list of lists of strings List<List<String>> Now the compiler keeps track of whether you have a list of integers (or strings or lists of strings), and no explicit cast back to Integer (or String or List<String>) is required. In some ways, this is similar to generics in Ada or templates in C++, but the actual inspiration is parametric polymorphism as found in functional languages such as ML and Haskell. Part I of this book provides a thorough introduction to generics. We discuss the inter- actions between generics and subtyping, and how to use wildcards and bounds; we xi describe techniques for evolving your code; we explain subtleties connected with casts and arrays; we treat advanced topics such as the interaction between generics and se- curity, and how to maintain binary compatibility; and we update common design pat- terns to exploit generics. Much has been written on generics, and their introduction into Java has sparked some controversy. Certainly, the design of generics involves swings and roundabouts: making it easy to evolve code requires that objects not reify run-time information describing generic type parameters, but the absence of this information introduces corner cases into operations such as casting and array creation.We present a balanced treatment of generics, explaining how to exploit their strengths and work around their weaknesses. Part II provides a comprehensive introduction to the Collections Framework. Newton is reputed to have said, “If I have seen farther than others, it is because I stand on the shoulders of giants”. The best programmers live by this motto, building on existing frameworks and reusable code wherever appropriate.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    285 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us