Book: Java Generics and Collections

During preparations for a job interview I noticed that my understand of Java Generics had some holes in it; and during the interview itself it became clear that there were also a few holes in my knowledge about the corner cases of the Java Collections framework introduced with Java 5 and 6. So, after looking around a bit, which book could be more suiting than Java Generics and Collections?

Now, I wasn’t completely lost for either of the two, but they were both introduced after I had my Java programming course (in Java 1.4) and apparently since then there hasn’t been a situation requiring much more than your typical

List<String> strList = new ArrayList<String>();

and the like (perhaps there rarely are?). However, when I came across the follwing signature:

public static <T extends Comparable<? super T>> T max(
    Collection<? extends T> coll) {
    // iterate to find max ...
}

it was clear that there was something not so trivial going on; a nice little example of why this crooked specification is useful is given in Section 3.3, but funnily enough I find the use of keywords extends and super a bit counter-intuitive here — mostly likely because I’ve “grown up” with the formal <: notation instead.

Now, in general the chapters on generics are well-written and usefully sprinkled with illustrative examples. There could sometimes have been more technical explanations, and perhaps links to formal type theory (it was written by Philip Wadler after all), however, overall it’s a highly recommended read!

It even taught me a little peculiar thing about Java bytecode, namely that generics allows one to overload methods based on return type:

class Works {

    public static void main(String[] args) {
        Works o = new Works();
        int i = o.<Integer>foo();
        boolean b = o.<Boolean>foo();
    }

    public <T extends Integer> int foo() {
        return 0;
    }

    public <T extends Boolean> boolean foo() {
        return false;
    }

}

which wouldn’t compile without generics:

class DoesntWork {

    public static void main(String[] args) {
        DoesntWork o = new DoesntWork();
        int i = o.foo();
        boolean b = o.foo();
    }

    public int foo() {
        return 0;
    }

    public boolean foo() {
        return false;
    }

}

since the compiler doesn’t know which method to pick in main. However, the bytecode calls a method by looking up in an index table, and with generics the compiler has enough information to differentiate these.

For the second part of the book, on the Collection framework, the book disappoints a bit: it covers most classes and uses, but few details are given and there’s quite a bit of fluff. It gave me the overview I needed, but not much more than going over the online Java documentation.

Leave a Reply

Your email address will not be published.