Java 8-为什么他们提供了方法引用? [英] Java 8 - why they provided method references?

查看:51
本文介绍了Java 8-为什么他们提供了方法引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通话方面有什么优势

names.stream().forEach(System.out::println);

names.stream().forEach(n -> System.out.println(n));

尽管您实际上需要编写更少的代码?在Java 8中引入方法引用还有其他优点吗?

Despite the fact you have to write less code? Are there any other advantages of introducing method references in Java 8?

推荐答案

尽管您实际上需要编写更少的代码?在Java 8中引入方法引用还有其他优点吗?

Despite the fact you have to write less code? Are there any other advantages of introducing method references in Java 8?

只需编写更少的代码就足以考虑引入语言功能. C#中有一个类似的功能,称为 方法组 ,它使编写代码更加容易使用委托. Lambda是匿名类的简写,而匿名类可被视为命名类的简写.人们可以合理地称它们为语法糖",但是所有这些功能都可以帮助您减少代码编写.

Having to write less code is enough of an advantage to consider introducing a language feature. There is a similar feature in C#, called method groups, that makes it easier to write code that uses delegates. Lambdas are shorthand for anonymous classes, and anonymous classes could be considered shorthand for named classes. One could legitimately call them "syntactic sugar", yet all these features help you write less code.

除了可以缩短代码之外,该功能还具有帮助Java编译器设计人员生成更高效代码的潜力.例如,有可能避免为包装方法引用的每个lambda生成全新的类型.

In addition to letting you shorten the code, the feature has a potential of helping designers of Java compiler generate more efficient code. For example, it might be possible to avoid generating a brand-new type for each lambda wrapping a method reference.

这篇关于Java 8-为什么他们提供了方法引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆