Java Generics demystified

After having just bashed one book, I need to do something for the Yin/Yang balance. So, here’s a book recommendation:

Book: Java Generics and Collections

Book: Java Generics and Collections

While one may sometimes think that books on programming languages are obsolete with everything out there on the Internet, there are situations when after researching for hours, reading tutorials, blogs reiterating the tutorials, etc., you wish you just had somebody with some real in-depth knowledge to explain things to you. If the matter in question is generics in Java, I can absolutely recommend this book by Maurice Naftalin (funny last name, though) and Philip Wadler. It goes way beyond what the vast majority of tutorials explain. You might find everything in the Java Language Specification, but this book is certainly easier to consume.

It has solved these questions for me:

  • Q: How do you subclass a class with fairly wide type bounds in such a way that you restrict the bounds but not just select a parent further down the chain? For example, you may want to allow just one specific type.
    A: You don’t put the type in the declaration of your child class, but in its extends/implements clause. So, you don’t do:

    public MyMap<String, MyObject> extends AbstractMap {

    You could potentially do:

    public MyMap<K extends String, V extends MyObject> extends AbstractMap {

    Since String is final, that may be OK, but are you safe on V? Maybe, maybe not.
    To pin this down, you could do:

    public MyMap extends AbstractMap <String, MyObject> {
  • Q: How do you use a generic method when the type cannot be inferred from the method parameter (e. g. because there is none)?
    A: Let’s say you have a method like this:

    public class MyClass<T extends Blah> {
    public List<T> getList()

    And then you want to call this from another generic class. The following may work but -Xlint:unchecked complains.

    public class MyOtherClass<T extends Blah> {
    MyClass<T> foo;
    List<T> bar = foo.getList();

    The clean way to do it, is:

    List<T> bar = foo.<T>getList();

If you’re interested, you’ll find the book with this information:

Title: Java Generics and Collections
Authors: Maurice Naftalin, Philip Wadler
Published: October 2006
Pages: 284
ISBN 10: 0-596-52775-6 | ISBN 13: 9780596527754

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: