The Diamond Operator Is Your Friend

December 25, 2012  |  Less than 1 minute to read


Heads up! This is an old post - it may contain out-of-date information!

Java 7 introduced a new operator - <> - referred to as the “diamond” operator. This new keystroke-saving syntax allows you to maintain the benefits of compile-time generics without typing out long strings of redundant type parameters. Prior to Java 7, creating and initializing a variable with nested type parameters was an arduous task:

HashMap<TreeSet<TreeMap<String, Integer>>, Double> myTerribleDataStructure =
    new HashMap<TreeSet<TreeMap<String, Integer>>, Double>();
A bunch of diamonds
Diamond (operators) are a girl's Java developer's best friend.

The diamond operator greatly simplifies this unnecessary complexity. The following is semantically identical to the above example:

HashMap<TreeSet<TreeMap<String, Integer>>, Double> myTerribleDataStructure = new HashMap<>();

Note that this is not the same as:

HashMap<TreeSet<TreeMap<String, Integer>>, Double> myTerribleDataStructure = new HashMap();

Without the diamond operator, myTerribleDataStructure is initialized to the raw HashMap type instead of its type-specific counterpart.


Other posts you may enjoy:

Live Reloading An Angular 2+ App Behind NGINX

May 14, 2018  |  4 minutes to read

Fantastic Fast Fonts with system-ui

April 27, 2018  |  1 minute to read

Smart Date Searching with Solr

June 26, 2017  |  5 minutes to read

Inspirograph

January 26, 2015  |  5 minutes to read

Auto-Ejecting Event Handlers

March 6, 2013  |  1 minute to read