Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-08-26 22:29:07
forward
551 people have browsed it

在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());
      }
   }
}
Copy after login

Output

<strong>Raja
Adithya
Jai
Chaitanya
Vamsi</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template