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