Java Generics diamond operator (type inference)
- Details
- Written by Nam Ha Minh
- Last Updated on 17 August 2019   |   Print Email
Before Java SE 7, we have to write code to create new instances of generic types as follows:
List<Integer> numbers = new ArrayList<Integer>();
Or more complex:
Map<String, String> simpleMap = new HashMap<String, String>();
Or even more complex:
Map<String, List<Integer>> complexMap = new HashMap<String, List<Integer>>();
Why do we have to declare the parameter types on both side? The parameter types on the right-hand side seem to be redundant, right? So in Java 7 and later, developer can now replace the right-hand side parameters with an empty set of parameters like this:
List<Integer> numbers = new ArrayList<>(); Map<String, String> simpleMap = new HashMap<>(); Map<String, List<Integer>> complexMap = new HashMap<>();
The angle brackets <> are informally called the diamond operator. The Java compiler can infer the types based on the left-hand side (thus the term type inference). This is a simple language improvement but it greatly simplifies generic instance creation (of course the old way still works) and saves us a lot of code!
Related Tutorials:
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Java Variables Passing Examples - Pass-by-value or Pass-by-reference?
- Understand Encapsulation in Java
Comments
List