Switch to the Czech version

Thursday, 19 January 2012

Diamond in Java 7

After writing this kind of line of code...

Box<Integer> integerBox = new Box<Integer>();

...my all-knowing IDE (NetBeans) has suggested that I use the diamond operator. What is that? Good question. Apparently this is one of the new features in Java 7. If the compiler can infer the type arguments, you can leave the brackets empty, i.e. use a diamond. The code then looks like this...

Box<Integer> integerBox = new Box<>();

...which is a bit better, because I always hated having to type the same arguments on two places (on a single line). Nice one, Java!

More on this: docs.oracle.com - generics tutorial
Also, this is why we don't just drop the diamond all together: stackoverflow.com thread

No comments:

Post a Comment