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!
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments
List