Saturday, July 30, 2011

Java 7: Diamond Operator

The diamond operator (<>) removes the need for explicit type arguments in constructor calls to generic classes, thereby reducing visual clutter. For example:
//previously:
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();

//in jdk7, use the diamond operator. Saves typing!
Map<Integer, List<String>> map2 = new HashMap<>();

List<?> list = new ArrayList<>();
The compiler infers the type on the right side. So if you have a list of ?, the compiler will infer a list of Object.

Eclipse support:

  • Eclipse Content Assist (Ctrl + Space), auto-completes using a diamond instead of explicit type arguments. So, in the example above, when you type new HashM[Ctrl+Space], Eclipse will insert new HashMap<>();.

  • You can also configure Eclipse to warn you if you use explicit type arguments, instead of a diamond. To do this, go to your Preferences and navigate to Java > Compiler > Errors/Warnings. In the Generic types section, select Warning against Redundant type arguments. Eclipse will then offer you a quick-fix to remove the type arguments, if you accidently put them in.
Further Reading:
Type Inference for Generic Instance Creation

No comments:

Post a Comment