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.
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.
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:
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.
- Magic Cast Method in Java