How do I use the diamond syntax?

In Java 7 a new feature called diamond syntax or diamond operator was introduced. This diamond syntax <> simplify how we instantiate generic type variables. In the previous version of Java when declaring and instantiating generic types we’ll do it like the snippet below:

List names = new ArrayList();

Map<string, list<integer="">> map = new HashMap<string, list<integer="">>();

As you can see in the snippet, we were repeating our self by defining the generic type two times. We define the object type we’ll be stored in the List and the Map on both left and the right side. By using the diamond syntax the compiler will infer the type of the right side expression argument automatically. So in Java 7 we can write the above code snippet like this:

List names = new ArrayList<>();

Map<string, list<integer="">> map = new HashMap<>();

This make our code simpler and more readable and by using the diamond syntax the compiler will ensure that we have the generic type safe checking available in our code. This will make any error due to type incompatibility captured at the compile time.

Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply