Nicer Collection Instantiation In Java

In my last post I showed that you can write a ‘cast’-method with all kind of strange properties. You probably think that this is very stupid thing to do. This time I show a more useful application of the same behavior.

Nice Factories For Collections

Nice Factories For Collections

Think about all the places in your code where you create an instance of a collection. Lots of places, right? Anyway you always have to write down the type and generic arguments twice, which is very annoying. That’s why in Java 7 the diamond operator will be introduced.

// Annoying double declaration of the generic arguments
List<String> strings = new ArrayList<String>();

// Even more annoying
Map<String,URI> cityToWebsite = new HashMap<String,URI>();

Luckily you don’t need to wait until Java 7 to improve the situation. This is place where generic type inference comes handy. You can create static factory methods for often used types such as lists, maps, sets etc. Then you can statically import those methods and use them instead of newing up the objects. The big advantage is that the generic arguments are inferred by the compiler and you don’t need to specify them twice. Here’re the utility methods:

And here’s the usage. Note that we’re using static imports for the methods:

List<String> strings = list();
List<String> moreStrings = list("Hi","There");

Set<String> setOfStrings = set();

Map<String,URI> cityToWebsite = map();

By the way this tricky also used in the the JDK libraries for the Collections.emptyList(), emptySet() and emptyMap() methods.

That’s it for now. Try it out and build your own set of static factory methods. It’s a nice way to get rid of chatty and useless type declarations.

Tagged on: ,

One thought on “Nicer Collection Instantiation In Java

Leave a Reply

Your email address will not be published. Required fields are marked *