Home  >  Article  >  Java  >  In Java 9, can I use diamond operator in anonymous inner classes?

In Java 9, can I use diamond operator in anonymous inner classes?

WBOY
WBOYforward
2023-08-26 22:29:07552browse

在Java 9中,可以在匿名内部类中使用钻石操作符吗?

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.

Example

import 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());
      }
   }
}

Output

<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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete