Wednesday, January 04, 2012

Collection Literals in Java (or a hidden gem in Eclipse JDT)

Yesterday I watched a devoxx presentation by Joshua Bloch about the Evolution of Java" which I enojoyed.
In that talk he discusses the various language features which have been added to Java in terms of how important resp. problematic their addition was. I agree with most of his reasoning but not with the following two:

  • static imports
    He said they are ok, but not too useful and that he makes use of them only about once a month.
  • diamond operator
    He claimed, that this was an important addition, since now creating new collections is less noisy.

I disagree for the following reasons

Joshua Bloch actually also helped designing a very cool collection library which is part of Google Guava. If you don't know it, have a look! Besides other useful stuff that library contains factory methods for the common collection types.
For instance to create an ArrayList you could write the following:

List<String> names = Lists.newArrayList();

Making use of a static import one can write something like this:

import static com.google.common.collect.Lists.*;
...
List<String> stuff = newArrayList("Foo","Bar","Baz");

But the inconvenience of adding a static import every time you want to create a new collection is a problem. JDT to the rescue! There is an almost hidden gem in JDT, that allows you to have static import favorites for content assist. This is my configuration:



Having your static imports configured here, will make their methods available through code completion without having an import first. Instead the import will automatically be added as you apply the proposal.


I only create collections that way, because it's so easy and readable, and I don't have much use cases for the diamond operator (in fact inference on the left hand side would have been much more interesting). On the other hand I use static imports in almost any class file.

Btw, those static imports not only make the factory methods available but also all the nice higher-order functions like, collect, filter, etc..
A welcome productivity gain!