当前位置:首页 > JAVA教程 > JAVA基础

Java 9 钻石操作符(Diamond Operator)

java 9 钻石操作符(diamond operator)

钻石操作符是在 java 7 中引入的,可以让代码更易读,但它不能用于匿名的内部类。

在 java 9 中, 它可以与匿名的内部类一起使用,从而提高代码的可读性。

考虑以下 java 9 之前的代码:

实例

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

执行输出结果为:

1
2
test

在 java 9 中,我们可以在匿名类中使用 <> 操作符,如下所示:

实例

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

执行输出结果为:

1
2
test

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!