Java 9 Diamond Operator With Example

The diamond operator feature was introduced in Java 7. Using of Diamond operator from Java 7 onwards there is no need to mention generic type on the right-hand side of the expression.

How to declare Diamond Operator in Java?

// This is prior to Java 7. We have to explicitly mention the generic type
// on the right side as well. 
List<String> myList = new ArrayList<String>();
// Java 7 onwards, no need to mention generic type on the right side
List<String> myList = new ArrayList<>();

Problem with Diamond Operator while using Annonymous Inner class

Until Java 8 Diamond Operator allows us to use it in normal class only. This Diamond Operator is not allowed to anonymous inner class in Java.

Example

abstract class MyTest<T>{  
    abstract T msg(T a, T b);  
}  
public class Example {  
    public static void main(String[] args) {  
      MyTest<String> t=new MyTest<>() { 
            String msg(String a, String b) {  
                return a+b;   
            }  
        };    
        String output = t.msg("Hello"," Programmer");  
        System.out.println(output);  
    }  
}

Output

java:6: error: cannot infer type arguments for MyTest<T> 
???????MyTest<String> t=new MyTest<>(){ 
reason: cannot use '<>' with anonymous inner classes
where T is a type-variable:
T extends Object declared in class MyTest
1 error

We got a compilation error when we ran this above example until Java 8.

Java 9 – Diamond Operator Enhancement

From Java 9 onwards Diamond Operator is allowed to use in anonymous classes also. This is the enhancement of Diamond Operator in Java 9.

Example

abstract class MyTest<T>{  
    abstract T msg(T a, T b);  
}  
public class Example {  
    public static void main(String[] args) {  
      MyTest<String> t=new MyTest<>() { 
            String msg(String a, String b) {  
                return a+b;   
            }  
        };    
        String output = t.msg("Hello"," Programmer");  
        System.out.println(output);  
    }  
}

Output

Hello Programmer

Conclusion

In this topic, we learnt about Diamond Operator in Java, the Diamond Operator anonymous inner class problem until Java 8 and Diamond Operator enhancement in Java 9.

Leave a Comment