The Diamond Operator in Java 7
The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a closed angle bracket resembling a diamond's form (>). It may eliminate type and repetitive writing in Java when utilized appropriately, resulting in considerably simpler and understandable code, particularly when Generics are employed.
We frequently use the Diamond operator in Java when establishing and initializing structures containing several Generic types, such as a Map that contains another Map; as a result of enhanced category deduction, we need to specify the input text on the left flank of the statement.
Before Java 6, generic type inferences in Java were weak. The reasons must be stated on both the local variable's right and left sides. This makes code too complex and difficult to comprehend, particularly when hierarchical types are used, such as Map with Entry, where the key is String, and the value is a List of Integer numbers.
// the syntax of the diamond operator
// it is used on both sides of the class while creating an instance
List<String> list = new ArrayList<String>();
Since the introduction of the Diamond operator in Java 7, we may construct objects without specifying a generic type upon the right side of the statement, like :
List<String> lists = new ArrayList<>();
Problems due to the diamond operator are:
We may generate an object using the Diamond operator before stating the generic type here on the right side of the statement. However, it's only going to function with regular courses. If you try to execute the diamond operators on an unnamed inner class, the compiler will produce the following error.
Example: DiamondProgram.java
//this program is for the diamond operator in java
//importing the packages
import java.io.*;
import java.util.*;
abstract class Diamond<Temp> {
abstract Temp addition(Temp num1, Temp num2);
}
public class DiamondProgram {
public static void main(String[] args)
{
Diamond<Integer> object = new Diamond<>() {
Integer addition(Integer num1, Integer num2)
{
return (num1 + num2);
}
};
Integer res = object.addition(1001, 2002);
System.out.println("The sum of the 2 numbers is: " + res);
}
}
By enabling the diamond operator's usage with anonymous inner classes, Java programmers expanded the diamond operator's functionality in JDK 9. With JDK 9, the previous code will function as intended and provide the output below.
Output
The sum of the 2 numbers is: 3003