Before Java 7, while using generics we had to supply type parameters to variables types and to their actual types. Now, it has been relieved a bit in this new Java 7 feature. And a blank Java diamond operator on right side of declaration will work fine.
Diamond operator are denoted with two angles
1. Before generics – raw type declarations
If you have worked on early versions on Java (before 1.5), when generics were not a Java feature, developers have to use raw types declarations and initializations. For example, given below is a
Map params = new HashMap();
The problem with this approach is that you can put any object type in key and value, and only in runtime you will get error if object is not of desired type. There is no compile time safety which can warn developers, that which types are allowed and which are not.
2. Generics – parameterized types
JDK 1.5 brought generics. It must much needed feature and completely changed the way developers write the code. It enabled compile time safety. It helped in reducing runtime errors by great number.
Map<String, Integer> params = new HashMap<String, Integer>();
This syntax solves the problem of compile time type safety. In fact, above syntax is good for almost all use-cases. In above example, if you try to add any key or value of different type, compiler will give you error.
You need to fix your code to get through the compiler.
3. Diamond operator
Parameterized types solves issues but seems heavy due to same repeated type information on both sides. We can reduce the syntax if we can provide type information on one side, and other side can detect and apply the type information.
Diamond operator in Java does exactly the same thing. It is also called Elvis operator. Look below at diamond operator syntax.
Map<String, Integer> params = new HashMap<>();
In above code, compiler is smart enough in to identify that diamond operator infer to type defined on left hand side of declaration. It apply the type information to right side object as well. It helps in adding type inference feature to Java.
4. Backward compatibility
Raw types and parameterized types still exist for the sake of backward compatibility. But new compilers will warn if they see raw types. If you compile raw types with Java 5 onward, you will get warning like this:
ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized
Happy Leaning !!