File Name: collections and generics in java .zip
Jakob Jenkov Last update:
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
Generics and Collections Framework
All rights reserved. Printed in the United States of America. Published by 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.
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 contained herein. TM This book uses RepKover, a durable and flexible lay-flat binding. Generics 1. Collections 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 of strings list of lists of strings List List 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.
Part I of this book provides a thorough introduction to generics. We discuss the interactions between generics and subtyping, and how to use wildcards and bounds; we xi.
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. 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. The Java Collections Framework provides reusable interfaces and implementations for a number of common collection types, including lists, sets, queues, and maps. There is also a framework for comparing values, which is useful in sorting or building ordered trees.
Of course, not all programmers exploit reuse. As Hamming said of computer scientists, Instead of standing on each other s shoulders, we stand on each other s toes. Thanks to generics, code using collections is easier to read and the compiler will catch more type errors. Further, collections provide excellent illustrations of the use of generics. One might say that generics and collections were made for each other, and, indeed, ease of use of collections was one of the main reasons for introducing generics in the first place.
Java 5 and 6 not only update the Collections Framework to exploit generics, but also enhance the framework in other ways, introducing interfaces and classes to support concurrency and the new enum types. We believe that these developments mark the beginning of a shift in programming style, with heavier use of the Collections Framework and, in particular, increased use of collections in favor of arrays.
In Part II, we describe the entire framework from first principles in order to help you use collections more effectively, flagging the new features of Java 5 and 6 as we present them. Following common terminology, we refer to the successive versions of Java as 1. We say Java before generics to refer to Java 1. Odersky s GJ compiler is the basis of Sun s current javac compiler. For help using ftpmail, send an to with no subject and the single word help in the body of the message.
We often omit standard imports. Code that uses the Java Collection Framework or other utility classes should be preceded by the line: import java. Note: Recompile with -Xlint:unchecked for details. In general, you may use the code in this book in your programs and documentation.
You do not need to contact us for permission unless you re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission.
Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. Copyright O Reilly Media, Inc. Safari offers a solution that s better than e-books. It s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information.
Try it for free at Acknowledgments The folks at Sun past and present were fantastically good about answering our questions. They were always happy to explain a tricky point or mull over a design tradeoff.
Darcy, Neal M. We received comments and help from a number of people. We enjoyed reading Heinz M. Our editor, Michael Loukides,was always ready with good advice. Paul C. Our families kept us sane and insane. Preface xv. This part of the book describes generics, using the Collections Framework as a source of examples.
A comprehensive introduction to the Collections Framework appears in the second part of the book. The first five chapters focus on the fundamentals of generics. Chapter 1 gives an overview of generics and other new features in Java 5, including boxing, foreach loops, and functions with a variable number of arguments. Chapter 2 reviews how subtyping works and explains how wildcards let you use subtyping in connection with generics. Chapter 3 describes how generics work with the Comparable interface, which requires a notion of bounds on type variables.
Chapter 4 looks at how generics work with various declarations, including constructors, static members, and nested classes. Chapter 5 explains how to evolve legacy code to exploit generics, and how ease of evolution is a key advantage of the design of generics in Java. Once you have these five chapters under your belt, you will be able to use generics effectively in most basic situations.
The next four chapters treat advanced topics. Chapter 6 explains how the same design that leads to ease of evolution also necessarily leads to a few rough edges in the treatment of casts, exceptions, and arrays.
The fit between generics and arrays is the worst rough corner of the language, and we formulate two principles to help you work around the problems. Chapter 8 contains advice on how to use generics effectively in practical coding. We consider checked collections, security issues, specialized classes, and binary compatibility. Chapter 9 presents five extended examples, looking at how generics affect five well-known design patterns: Visitor, Interpreter, Function, Strategy, and Subject-Observer.
We begin with an example that illustrates all of these. As we shall see, combining them is synergistic: the whole is greater than the sum of its parts. Taking that as our motto, let s do something simple with sums: put three numbers into a list and add them together.
The interface List and the class Arrays are part of the Collections Framework both are found in the package java. Boxing and unboxing operations, used to convert from the primitive type to the wrapper class, are automatically inserted. The static method aslist takes any number of arguments, places them into an array, and returns a new list backed by the array. The new loop form, foreach, is used to bind a variable successively to each element of the list, and the loop body adds these into the sum.
The assertion statement introduced in Java 1. Now it is the coder rather than the compiler who is responsible for remembering the type of the list elements, so you must write the cast to Integer when extracting elements from the list. Without boxing and unboxing, you must explicitly allocate each object belonging to the wrapper class Integer and use the intvalue method to extract the corresponding primitive int. Without functions that accept a variable number of arguments, you must explicitly allocate an array to pass to the aslist method.
Without the new form of loop, you must explicitly declare an iterator and advance it through the list. Collections let you easily grow or shrink the size of the collection, or switch to a different representation when appropriate, such as a linked list or hash table or ordered tree.
The introduction of generics, boxing and unboxing, foreach loops, and varargs in Java marks the first time that using collections is just as simple, perhaps even simpler, than using arrays. Now let s look at each of these features in a little more detail. We saw one example in the previous section.
This trivial code fragment declares the variable words to contain a list of strings, creates an instance of an ArrayList, adds two strings to the list, and gets them out again. In Java before generics, the same code would be written as follows: 4 Chapter 1: Introduction. In fact, the bytecode compiled from the two sources above will be identical. We also use erasure to describe the process that converts the first program to the second.
The term erasure is a slight misnomer, since the process erases type parameters but adds casts. Generics implicitly perform the same cast that is explicitly performed without generics. If such casts could fail, it might be hard to debug code written with generics. This is why it is reassuring that generics come with the following guarantee: Cast-iron guarantee: the implicit casts added by the compilation of generics never fail.
Generics in Java
Q: 01 Given:. What, inserted at line 39, will sort the keys in the props HashMap? Answer: B. Q: 02 Click the Exhibit button. Which statement is true about the set variable on line 12? The set variable contains all six elements from the coll collection, and the order is guaranteed to be.
Generics are a facility of generic programming that were added to the Java programming language in within version J2SE 5. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety". The Java collections framework supports generics to specify the type of objects stored in a collection instance. According to Java Language Specification : . The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object.
Java Generics and Collections By Philip Wadler, Maurice Naftalin ISBN: This PDF is exclusively for your use in accordance with the Safari Terms of Service.
Java generics and collections
Explore a preview version of Java Generics and Collections right now. This comprehensive guide shows you how to master the most importantchanges to Java since it was first released. Generics and the greatlyexpanded collection libraries have tremendously increased the power ofJava 5 and Java 6. But they have also confused many developers whohaven't known how to take advantage of these new features. Java Generics and Collections covers everything from the mostbasic uses of generics to the strangest corner cases.
Skip to search form Skip to main content You are currently offline. Some features of the site may not work correctly. Wadler Published Computer Science.
This comprehensive guide shows you how to master the most important changes to Java since it was first released. Generics and the greatly expanded collection libraries have tremendously increased the power of Java 5 and Java 6. Java Generics and Collections covers everything from the most basic uses of generics to the strangest corner cases. Generics and the new collection libraries they inspired take Java to a new level. If you want to take your software development practice to a new level, this book is essential reading.
Generics in java were introduced as one of features in JDK 5. To be very frank, I have been using generics since a long time now but still I feel not fully confident to use it blindly. In this tutorial, I will be covering everything I find useful with java generics , and things related to them.
На полу возле тела Хейла лежал листок бумаги. Сьюзан наклонилась и подняла. Это было письмо. Дорогие друзья, сегодня я свожу счеты с жизнью, не в силах вынести тяжести своих грехов… Не веря своим глазам, Сьюзан медленно читала предсмертную записку. Все это было так неестественно, так непохоже на Хейла, а список преступлений больше напоминал перечень сданного в прачечную белья. Он признался во всем - в том, как понял, что Северная Дакота всего лишь призрак, в том, что нанял людей, чтобы те убили Энсея Танкадо и забрали у него кольцо, в том, что столкнул вниз Фила Чатрукьяна, потому что рассчитывал продать ключ от Цифровой крепости.
- Я ничего не сделал. - Ничего не сделал? - вскричала Сьюзан, думая, почему Стратмор так долго не возвращается. - Вы вместе с Танкадо взяли АНБ в заложники, после чего ты и его обвел вокруг пальца. Скажи, Танкадо действительно умер от сердечного приступа или же его ликвидировал кто-то из ваших людей.
В тот момент, когда он поравнялся с сиденьем, на котором сидела девушка, и подумал, что именно ей скажет, автобус проехал под уличным фонарем, на мгновение осветившим лицо обладателя трехцветной шевелюры. Беккер смотрел на него, охваченный ужасом. Под густым слоем краски он увидел не гладкие девичьи щеки, а густую щетину. Это был молодой человек.
Сирена выла не преставая. Сьюзан подбежала к. - Коммандер. Стратмор даже не пошевелился.
Дэвид Беккер. - Он пожал ее руку. - Примите мои поздравления, мистер Беккер. Мне сказали, что вы сегодня отличились. Вы позволите поговорить с вами об .
В дальнем углу, прямо под табло, которое когда-то показывало счет проходивших здесь матчей, он увидел слегка покосившуюся телефонную будку.