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<String> names = new ArrayList<String>();
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<String> 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 compile time.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024