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:

Useful things I've 3D printed

November 25, 2024  |  10 minutes to read

GitLab Pages with multiple domains

October 14, 2024  |  3 minutes to read

Zoom light

May 31, 2024  |  6 minutes to read

I built a weird keyboard

June 26, 2023  |  14 minutes to read

Wordle Bot

January 25, 2022  |  6 minutes to read