Yes, starting from Java 9, we can use diamond operator with anonymous inner classes.
The purpose of using the diamond operator The diamond operator is to avoid redundant code and by no longer using the generic# on the right hand side ## Type to make it more readable on one side of the expression. Diamond Operator Only works with normalclasses, but not with anonymousinternalJava 7 Class in . If we try to use it with an anonymous inner class, the compiler will throw an error .
In the example below, we use the diamond operator with an anonymous inner class. Exampleimport java.util.*; public class DiamondOperatorTest { public static void main(String args[]) { String[] str = {"Raja", "Adithya", "Jai", "Chaitanya", "Vamsi"}; <strong>Iterator<String></strong> itr = new Iterator<strong><String></strong>() { <strong>// Anonymous inner class</strong> int i = 0; public boolean hasNext() { return i < str.length; } public String next() { if(!hasNext()) { throw new <strong>NoSuchElementException()</strong>; } return str[i++]; } }; while(itr.hasNext()) { System.out.println(itr.next()); } } }
<strong>Raja Adithya Jai Chaitanya Vamsi</strong>
The above is the detailed content of In Java 9, can I use diamond operator in anonymous inner classes?. For more information, please follow other related articles on the PHP Chinese website!