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:

I built a weird keyboard

June 26, 2023  |  14 minutes to read

Wordle Bot

January 25, 2022  |  6 minutes to read

Herding Gits

August 26, 2021  |  2 minutes to read

It's finally here! 🎉

May 7, 2021  |  1 minute to read

Capturing Alexa Errors with Sentry and GitLab

November 18, 2020  |  4 minutes to read