AngelikaLanger.com - Java Generics FAQs - Frequently Asked Questions (original) (raw)

| | Angelika Langer - Training & Consulting | | ------------------------------------------ |

HOME| COURSES| TALKS| ARTICLES| GENERICS| LAMBDAS| IOSTREAMS| ABOUT| CONTACT| Twitter| Lanyrd| Linkedin

Books

HOME
GENERICS FAQ CONTENT FUNDAMENTALS FEATURES PRACTICAL TECHNICAL INFORMATION GLOSSARY INDEX PDF VERSION
LAMBDAS
IOSTREAMS
ABOUT
CONTACT

Java Generics FAQs - Frequently Asked Questions

This is a collection of answers to frequently asked questions (FAQs) about Java Generics, a new language feature added to the Java programming language in version 5.0 of the Java Standard Edition (J2SE 5.0).

If you want to provide feedback or have any questions regarding Java generics, to which you cannot find an answer in this document, feel free to send me EMAILor use the GENERICS FAQform.
A printable version of the FAQ documents is available in PDFformat (4.5MB).

Java Generics FAQs - Frequently Asked Questions

About This FAQ

© Copyright 2004-2022 by Angelika Langer. All Rights Reserved.

How is this FAQ organized at large?

The FAQ has 4 major sections: Fundamentals of Java Generics Language Features of Java Generics Practicalities - Programming With Java Generics Technicalities - Under the Hood of the Compiler "Fundamentals of Java Generics" explains the very basics of Java generics, what generics are and what their purpose and benefit is. "Language Features of Java Generics" is a huge section that explains all language features of Java Generics: Generic Types Generic Methods Type Parameters Type Arguments This section can be seen as the theoretical foundation and lays the ground for understanding more practical and more advanced issues. "Practicalities - Programming With Java Generics" aims to address issues that arise when you use Java Generics in practice. It discusses topics such as "How do I design a generics API?" , "Should my class be generic or not?", "What happens when I mix generic and non-generic Java?", "Why is class Class generic and what is this good for?". The focus is on programming techniques on the one hand and pitfalls and surprises on the other hand. It is likely that this section will grow over time as programming idioms and techniques using Java Generics will be discovered. "Technicalities - Under the Hood of the Compiler" addresses more advanced and more esoteric aspects of Java Generics, which will become the more interesting the more you learn about Java Generics. Some of these topics are typically of little interest when you begin using generics. For instance, the section explains what the notorious "unchecked" warnings are, what translation by type erasure is, what wildcard capture and type inference are, what the type system looks like now that it includes generic types, and how overload resolution works in presence of generic methods. In addition to these four main sections the FAQ has a Table Of Contents, a reference to More Information on Java Generics such as tutorials, books, articles, and websites, a Glossary, and an alphabeticIndex.
LINK TO THIS Preface.FAQ001
REFERENCES

How are the individual answered questions organized?

There is a question, a short answer and a sometimes fairly long answer, plus a cross reference section. I've found that many readers underestimate the reference section - to their own detriment. The cross references refer to related items and point in particular to entries that explain terms or facts mentioned in the text, but not explained there. In other words, if there is something in the explanation that has not been explained yet, go to the reference section and see whether you can find a reference to a corresponding entry that explains it. If not, let me know.
LINK TO THIS Preface.FAQ002
REFERENCES

Whom is the FAQ for?

For practicing Java programmers who have to do with Java Generics.
First a disclaimer: the FAQ does not aim to be mainly a tutorial. Tutorials can be found elsewhere. It has tutorial style answers, but it goes beyond what a casual or first-time generics user might want to know about Java Generics. On the other hand, it is still written for humans, as opposed to compiler builders or computer science theorists whose pet issue is type theory. While type theory is an interesting topic, the main target audience is programmers who use or want to use generics in practice. The FAQ is supposed to grow and mature over time. In particular the section on programming techniques using generics will hopefully gain weight as the body of experience with Java generics grows. If you have a technique or observation made in practice that you want to share with other programmers, feel free to send email and suggest it for inclusion in the FAQ.
LINK TO THIS Preface.FAQ003
REFERENCES [Where can I find a generics tutorial?](FAQSections/MoreInformation.html#Where can I find a generics tutorial?) [Whom do I contact when I have questions, comments or suggestions related to this FAQ?](JavaGenericsFAQ.html#Whom do I contact when I have questions, comments or suggestions related to this FAQ?)

How do I best read the FAQ - top-to-bottom or zig-zag?

Both should be possible.
The FAQ is kind of organized in a way that you can read it sequentially, starting with the first question until the bitter end. However, you will find that occasional jumps back and forth will be inevitable. For instance, when the language features are explained the term type erasure will be mentioned. Type erasure is part of what the compiler does during compilation and it is discussed in detail in the Technicalities section. So you will probably jump forward to the explanation of type erasure to see what it is in principle, spare yourself the details, and return to the language feature from which you started your excursion to the Technicalities section. Beyond that, the FAQ is mainly intended as a reference and can be consulted any order you feel like. Related topics are grouped together so that it might be convenient to read certain sections that are of immediate interest and ignore the rest for the time being. You might find that the same fact is explained repeatedly in different entries. This is intended. A certain amount of redundency is inevitable in order to make it possible to use the FAQ as a reference. If you feel you already know this, skip it and move on. Also, if you use the FAQ as a reference, the table of contents and the index should help finding what you are looking for. If not, let me know.
LINK TO THIS Preface.FAQ004
REFERENCES [Table Of Contents](JavaGenericsFAQ.html#Table Of Contents) Index Whom do I contact when I have questions, comments or suggestions related to this FAQ?

If you want to provide feedback or have questions regarding Java generics, to which you cannot find an answer in this document, feel free to send me EMAIL or use the GENERICS FAQ form. I might not be capable of answering in a timely manner or perhaps not at all, but I will try.
LINK TO THIS Preface.FAQ005
REFERENCES


Table Of Contents


Acknowledgements

The FAQ is written and maintained by Angelika Langer.

Klaus Kreft, Bruce Eckel and Cay Horstmann reviewed this FAQ and provided invaluable feedback.

A number of individuals at (or formerly at) Sun Microsystems (now Oracle) patiently answered countless questions I posed regarding Java generics. My thanks to Gilad Bracha, Neal Gafter, and Peter von der Ahé.

Suggestions and corrections, that inspired changes in this FAQ, have been provided by the following people (in alphabetic order): Eric Armstrong, Richard Grin, Markus Keller, Richard Kennard, Sascha Kratky, Keith Lea, Mike Lehmann, Maurice Naftalin, Joe Soroka, Frank Tip, Phil Wadler.

Change Log

Below is a list of minor and major modifications of the FAQ.

October 2004 First release.
January 2005 Terminology change. A reader pointed out that the draft of JLS 3 uses terms different from what I use in this FAQ document. This is because I started writing the FAQ before even a draft of JLS 3 was available. There still is no final specification of the language features of Java Generics. Nonetheless I decided to reduce the mismatch somewhat by changing some of the terms used throughout this document. The most significant deviation from the JLS 3 terminology is the use of the term "parameterized type". The JLS uses the term "parameterized type" to refer to types with a type argument list, such as ListorList. I used the term "parameterized type" to distinguish between types with type parameters, such as List, which is a type that declares a type parameter E that stands for the type of the elements in the list, and plain old types without type parameters, such as String,Date,Point, etc. Hence I made the following change: _formerly used in this FAQ_ \=> _now used in this FAQ (and in JLS 3)_ parameterized type/method \=> generic type/method instantiation of a parameterized type \=> parameterized type There remains an issue regarding use of the term "instantiation". The term "instantiation" is used in the JLS in conjunction with object creation: a type is instantiated to form an instance of the type, that is, an object of that type. I reuse the term "instantiation" to refer to the "creation" of a parameterized type from a generic type, that is, for the manifestation of a generic type such as Listwith its formal type parameter E as a parameterized type with an actual type argument as in List or List. This can be regarded as misleading, because nothing is created, not even a new type, different from what happens in C++ for instance when a template is instantiated. Yet I could not think of a more precise or adequate term that would denote the fact that formal type parameters are replaced by actual type arguments in a generic type or method. In other words, I "instantiate" generic types to form parameterized types, and I talk of "instantiations" of a generic type, which are the parameterized type, as opposed to "instances" of a type, which would be objects, like in the JLS.
May 2005 Updated the reference section; since April 19, 2005 the Java Language Specification, 3rd edition is available on the web at: http://java.sun.com/docs/books/jls/
August 2005 Corrected a couple of bugs. Affected are TypeArguments.FAQ103 , TypeArguments.FAQ104 , TechnicalDetails.FAQ501 , TechnicalDetails.FAQ502 , ProgrammingIdioms.FAQ201 , ProgrammingIdioms.FAQ303 . Added some new items: ProgrammingIdioms.FAQ006A , ProgrammingIdioms.FAQ050 , ProgrammingIdioms.FAQ302A thru ProgrammingIdioms.FAQ302C , TechnicalDetails.FAQ050 , TechnicalDetails.FAQ051 . Added a glossary in order to get the terminology straight. I noticed that documents originating from Sun Microsystems, such as the language specification (JLS 3) and the tutorial, use slightly different terms than you will find in books and articles from other sources. The glossary aims to list commonly used terms related to Java Generics and to explain what they denote and which ones are synonyms. The controversial terms are invocation/instantiation of generic/parameterized types/methods. The JLS talks of an invocation of a generic type or method, where most other authors talk of an _instantiation_of a generic type or method. Some authors equate generic type and parameterized type, while the JLS equates invocation and parameterized type.
October 2005 Added some stuff on overloading and overriding in the context of Java generics. The new items are: ProgrammingIdioms.FAQ051 and TechnicalDetails.FAQ801 thru TechnicalDetails.FAQ830 . Further additions: ProgrammingIdioms.FAQ103A , ProgrammingIdioms.FAQ201A , ProgrammingIdioms.FAQ300 , TechnicalDetails.FAQ007 , TechnicalDetails.FAQ402A , TechnicalDetails.FAQ609 .
December 2005 Added new item: TypeParameters.FAQ107 . Made available a PDF version of this FAQ document.
May 2006 Added new item: ProgrammingIdioms.FAQ205 .
November 2006 Added an additional example to item ProgrammingIdioms.FAQ300 . My thanks to Peter von der Ahé and Bob Lee for supplying the example.
December 2006 Added whole new section on Java Generics and Reflection: ProgrammingIdioms.Reflection . Corrected a mistake in entry TechnicalDetails.FAQ821 . My thanks to Jingyi Wang for spotting the mistake.
May 2007 Corrected some typos. My thanks to Oleksii Shurubura and Zhang Xu for spotting the bugs.Added new item describing the "getThis" trick: ProgrammingIdioms.FAQ206 .
October 2007 Corrected some typos. My thanks to Steven Adams and Seb Rose for spotting the bugs.
February 2008 Corrected some typos. My thanks to Liu Yuqing for spotting the bugs.German speaking readers might be interested in a series of articles that I made available at EffectiveJava .The articles are drafts of contributions to our "Effective Java" column published in a German print magazine in 2007.
March 2008 Corrected some typos. My thanks to Marcel Rüedi for spotting the bugs.
April 2008 Replaced an incorrect example in TypeParameters.FAQ402 by a more useful one and corrected a bug in TypeParameters.FAQ105 . My thanks to Jürgen Jäschke and Martin Goerg for spotting the bugs.
July 2008 Corrected some typos. My thanks to Rob Ross for spotting the bugs.Added some links and bookmarks to the PDF version of this FAQ document for better navigation. It is not perfect, but I hope it helps.
August 2008 Added a link and an additional example to Practicalities.FAQ603 . My thanks to Dan Frankowski for suggesting the addition.Rewrote Technicalities.FAQ402A because the compilers nowadays apply smarter type inference strategies than they did when the entry was written; as a result some of the source code examples were no longer meaningful. My thanks to Steven Busack for bringing the changes to my attention. Added two new entries Practicalities.FAQ207 and Practicalities.FAQ208 that describe a programming technique that Jesse Glick brought to my attention. Kudos to Jesse.
October 2008 Corrected some typos. My thanks to Gary Gregory for spotting the bugs.
August 2009 Corrected some typos. My thanks to Ganesh Hegde and Barry Soroka for spotting the bugs.
June 2010 Corrected bugs in Technicalities.FAQ103 and Technicalities.FAQ608 . My thanks to Clive Scott for spotting the bugs.
August 2010 Made an update to acknowledge additions and corrections intended for release with Java 7. Specifically, I added a couple of entries regarding the problem with varargs and generics, an explanation of the new varargs warning, and whether or not one can safely suppress the varargs warnings (see Practicalities.FAQ300A ). In addition, I added a section on the diamond operator, the improved type inference for instance creation expressions and its limitations (see Technicalities.FAQ400 ). My thanks to Maurizio Cimadamore of Oracle for a couple of clarifications. Corrected a typo. My thanks to Prasanth Jalasutram for spotting the typo.
May 2011 Corrected minor omission in Technicalities.FAQ824 . My thanks to Gene Carpenter for spotting the omission.
August 2011 Made a couple of minor adjustments in Practicalities.FAQ300A , Practicalities.FAQ300B , and Practicalities.FAQ300C due to differences between the prototype implementation and the final release of Java 7. Specifically, the annotation @SuppressWarnings("varargs")has been replaced by the @SafeVarargs annotation and the "varargs" warnings became plain "unchecked" warnings.
February 2012 Corrected some formatting and grammar issues. My thanks to Chris Dailey and Alan Frankel for spotting the deficiencies.
November 2012 Updated the section on related information such as books and websites (see Information.FAQ002 and InformationFAQ005 ).
February 2013 Corrected an error in Technicalities.FAQ400D regarding use of the diamond operator on anonymous inner classes. My thanks to Rabea Gransberger for spotting the bug.
April 2013 Updated the sections related to type parameter inference for invocation of generic methods and the diamond operator. Type inference has been changed and improved substantially for Java 8. Numerous situations that resulted in error messages in Java 5, 6, and 7 compile just fine in Java 8. The changes concern Technicalities.FAQ400C , Technicalities.FAQ400D , Technicalities.FAQ403 , Technicalities.FAQ405 .Updated entry TypeParameters.FAQ107 for clarification. The entry discusses the lack of lower bounds on type parameters, i.e., a feature that does not (yet) exist, but is occasionally considered useful for certain situations. I added examples in order to illustrate when the feature would be harmful or useful.
February 2014 Fixed an incorrect example in TypeParameters.FAQ102 . My thanks to Dheeru Mundluru for spotting the bug.
August 2014 A couple of corrections suggested by Moez AbdelGawad.
January 2015 Type inference was slightly modified in Java 8 which affected the example in Technicalities.FAQ404 . My thanks to Chad Berchek for bringing it to my attention and to Dan Smith of Oracle for explaining the type inference modification to me.
March 2015 Fixed a couple of typos in Technicalities.FAQ823 . My thanks to José María García Varona for spotting the glitches.
February 2016 Updated some sections to reflects language changes in Java 9: The diamond operator is permitted in anonymous class definitions ( Technicalities.FAQ400B ). The @SafeVarags annotation is permitted on private instance methods ( Practicalities.FAQ300B ).
August 2016 Uploaded a bunch of missing diagrams. My thanks to Xavier Tarrago for spotting the omission on my website.
April 2017 Added a missing topic in the table of contents. My thanks to Dan Fabulich for spotting the omission.
August 2017 Fixed a typo ( Practicalities.FAQ501 ). My thanks to Satrajit Acharyya for spotting it.
October 2017 Fixed a typo ( Technicalities.FAQ604 ). My thanks to Alessio Gaspar for spotting it.
August 2018 Fixed a misleading example ( TypeArguments.FAQ203 ). My thanks to Rishabh Gupta for bringing it to my attention.
Oktober 2018 Fixed a typo ( GenericTypes.FAQ104A ). My thanks to Rinat Akhmetov for spotting it.
May 2021 Fixed a typo ( TypeArguments.FAQ201 ). My thanks to Kent Hervey for spotting it.

All text and content found at URLs starting with http://www.AngelikaLanger.com/GenericsFAQ/ (collectively, "the Java Generics FAQ") are the sole property of Angelika Langer. Copyright @ 2004-2021 by Angelika Langer. All rights reserved.

Except as specifically granted below, you may not modify, copy, publish, sell, display, transmit (in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise), adapt, distribute, store in a retrieval system, create derivative works, or in any other way use or exploit the contents of the Java Generics FAQ, without the prior consent of the author.

All rights, titles and interest, including copyrights and other applicable intellectual property rights, in any of the material belongs to the provider of the material. You do not acquire proprietary interest in such materials by accessing them on my web site. You must abide by all copyright notices and restrictions on use of the material accessed.

In particular, I do NOT grant permission to copy the Java Generics FAQ or any part of it to a public Web server. Link to the original pages instead. (The problem with you putting a page on your server is that the search engines will find it and send my readers to your server instead. Thus they will be deprived of the most up-to-date version of the document.)

Non-commercial Use
As a reader of the Java Generics FAQ, you are granted a nonexclusive, nontransferable, limited license to access and use for non-commercial (research and information) purposes the materials that are made available to you as the Java Generics FAQ. This license includes the right to download and print out one copy of the Java Generics FAQ so long as you neither change nor delete any author attribution, legend or copyright notice. I request that you do not break up the document and attribute the source in such a way that someone can find the most up-to-date version on the Web, e.g. by including a link to http://www.AngelikaLanger.com/GenericsFAQ/JavaGenericsFAQ.html. If you redistribute the hardcopy of the Java Generics FAQ, please send me email informing me of the usage.

Other forms of non-commercial use may be allowed with prior written permission. If permission is granted for non-commercial use, credit to the copyright owner must be displayed as prescribed by copyright owner in every exposure of text. To request non-commercial use of copyrighted materials, please email your request and provide the following information: your name, organization, and title, your request (the text or texts you wish to quote) and the non-commercial purpose of the use.

Commercial Use

Commercial use on paper, electronic storage devices of all types, online via the Internet or any part of the World Wide Web or via any other electronic distribution is strictly prohibited without prior payment to the copyright owner, as well as attribution of ownership of copyright and URL in every exposure of text. To negotiate legal use of text owned and copyrighted by Angelika Langer, please send me email.

Disclaimers

The author has taken care in the preparation of this material, but makes no expressed or implied warranty of any kind and assumes no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the information or programs contained herein.


CONTENT NEXT INDEX

© Copyright 1995-2022 by Angelika Langer. All Rights Reserved. URL: <http://www.AngelikaLanger.com/GenericsFAQ/JavaGenericsFAQ.html> last update: 13 May 2021