English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented Programming(I)

Java Object-Oriented Programming(II)

Java Object-Oriented Programming(III)

Java Exception Handling

Java List(List)

Java Queue(Queue)

Java Map Collection

Java Set Collection

Java Input Output(I/O)

Java Reader/Writer

Java Other Topics

Java 9 Diamond Operator

Java 9 New Features

The diamond operator is in java 7 It can make the code more readable, but it cannot be used in anonymous inner classes.

Introduced in java 9 In this context, it can be used with anonymous inner classes to improve code readability.

Consider the following Java 9 Previous code:

public class Tester {
   public static void main(String[] args) {
      Handler<Integer> intHandler = new Handler<Integer>(1) {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      intHandler.handle();
      Handler<? extends Number> intHandler1 = new Handler<Number>(2) {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      intHandler1.handle();
      Handler<?> handler = new Handler<Object>("test") {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      handler.handle();    
   }  
}
abstract class Handler<T> {
   public T content;
 
   public Handler(T content) {
      this.content = content; 
   }
   
   abstract void handle();
}

The execution output is:

1
2
Test

In Java 9 In this context, we can use the <> operator in anonymous classes, as shown below:

public class Tester {
   public static void main(String[] args) {
      Handler<Integer> intHandler = new Handler<>(1) {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      intHandler.handle();
      Handler<? extends Number> intHandler1 = new Handler<>(2) {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      intHandler1.handle();
      Handler<?> handler = new Handler<>("test") {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
 
      handler.handle();    
   }  
}
 
abstract class Handler<T> {
   public T content;
 
   public Handler(T content) {
      this.content = content; 
   }
   
   abstract void handle();
}

The execution output is:

1
2
Test

Java 9 New Features