Can a diamond operator be used with an anonymous inner class in Java 9?

JavaObject Oriented ProgrammingProgramming

Yes, we can use the diamond operator with an anonymous inner class since Java 9.

The purpose of using a diamond operator is to avoid redundant code and make it more readable by no longer using a generic type on the right side of an expression. The diamond operator used only for normal classes but not for anonymous inner classes in Java 7. If we try to use it for anonymous inner classes, the compiler throws an error.

In the below example, we have used a diamond operator with an anonymous inner class.

Example

import java.util.*;
public class DiamondOperatorTest {
   public static void main(String args[]) {
      String[] str = {"Raja", "Adithya", "Jai", "Chaitanya", "Vamsi"};
      Iterator<String> itr = new Iterator<String>() {      // Anonymous inner class
         int i = 0;
         public boolean hasNext() {
            return i < str.length;
         }
         public String next() {
            if(!hasNext()) {
               throw new NoSuchElementException();
            }
            return str[i++];
         }
      };
      while(itr.hasNext()) {
         System.out.println(itr.next());
      }
   }
}

Output

Raja
Adithya
Jai
Chaitanya
Vamsi
raja
Published on 12-Feb-2020 12:51:03
Advertisements