Wednesday, August 10, 2011

JDK 7: Diamond Operator <>

JDK 7 is finally here and comes with it (among other niceties) the much needed syntactic sugar for type inference in generics declaration - the diamond operator (<>).

A declaration such as
Map<String, List<String>> map = new HashMap<String, List<String>>(); 

can now simply be written as
Map<String, List<String>> map = new HashMap<>();

The new operator <> automatically infers the type of the object we are creating based on the type declaration. If you leave out the <> it is still valid syntax of course, however, you will get a warning from the compiler for unchecked conversion like before.

Refer to the Java Tutorial page for more info on Generics Type Inference: http://download.oracle.com/javase/tutorial/java/generics/gentypeinference.html

Time to clean up some code!

No comments:

Post a Comment