In this post, we will discus the enhancement being made in Diamond operator in Java 9 release.
Check out: Iterate / ofNullable operations in Java 9 Stream
Diamond Operator Enhancement in Java 9...!!! Click To Tweet
In this article, we are going to cover below points:
- What is Diamond Operator?
- Problem with it in Java 7?
- How Java 9 solves that problem?
Let’s begin:
1. What is Diamond Operator?
It was introduced in Java 7 and it’s purpose is to avoid redundant code and make it more readable by no longer using the generic type on the right side of the expression.
Before Java 7:
Generic type was required to mention on the right side of the expression
1 | List<String> myList = new ArrayList<String>(); |
Since Java 7:
Generic type was NO LONGER required to mention on the right side of the expression. Instead, now we have ‘Diamond’ <> operator.
1 | List<String> myList = new ArrayList<>(); |
2. Problem with Diamond Operator in Java 7?
Well, as you’ve seen above that how you can use diamond operator BUT it worked for ‘normal’ classes only. If you try to use it for ‘anonymous inner’ classes, then compiler will throw the error message.
Let’s run the below code in Java 7:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Diamond_Operator_Java { public static void main(String[] args) { TestClass <Integer> abstractClassObj = new TestClass <> () { Integer multiply(Integer n1, Integer n2) { return n1 * n2; } }; Integer multiplyOfNumbers = abstractClassObj.multiply(50, 9); System.out.println("Multiplication of numbers: " + multiplyOfNumbers); } } abstract class TestClass <T> { abstract T multiply(T number1, T number2); } |
Java 7 Error message:
1 2 3 4 5 6 7 | Diamond_Operator_Java.java:7: error: cannot infer type arguments for TestClass TestClass abstractClassObj = new TestClass<>() { ^ reason: cannot use '<>' with anonymous inner classes where T is a type-variable: T extends Object declared in class TestClass 1 error |
3. How Java 9 solves the problem?
Java 9 improved the diamond operator by allowing diamond operator to be used with anonymous inner classes too. Lets run the same example(Diamond_Operator_Java.java) that we have seen above in Java 9.
It will work completely fine and will generate the below output.
Java 9 Output:
1 | Multiplication of numbers: 450 |
This is one a truly useful addition as part of Java 9. I hope above examples could help you to get better idea on how to implement it.
Diamond Operator Enhancement in Java 9...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts:
- dropWhile / takeWhile operations in Java 9 Streams
- Collection sorting using Lambda in Java 8
- Iterate / ofNullable operations in Java 9 Streams