Java方法参考字符串如何实现比较器< string>作品?
java.util.Comparator<String> lambda = (s1, s2) -> s1.compareTo(s2); // line 1
java.util.Comparator<String> methodRef = String::compareTo; // line 2
我不明白为什么第2行没有错误而工作,以及为什么它等效于第1行。第2行返回了接收字符串和返回的方法参考和int(IE int comparare(string s)),但是,比较器功能方法签名为
int comparare(t o1,t o2);
>
java.util.Comparator<String> lambda = (s1, s2) -> s1.compareTo(s2); // line 1
java.util.Comparator<String> methodRef = String::compareTo; // line 2
I can't understand why line 2 works without error, and why it is equivalent to line 1. Line 2 is returning a method reference that receives a string and returns and int (i.e. int compare(String s)
), however, comparator functional method signature is int compare(T o1, T o2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对
String::compareTo
的引用是一种特殊的方法引用,称为 “引用特定类型的任意对象的实例方法”。在这种情况下,编译器知道我们正在引用给定类的非静态方法,并且它可以转换为具有所需签名的函数接口。
例如:
lambda 状态 的第 8 点和第 9 点给出实施此方案的理由。
来自方法参考概述 youtube 视频
The ref to
String::compareTo
is a special kind of method reference called "Reference to an Instance Method of an Arbitrary Object of a Particular Type".In this case, the compiler knows that we are referencing a not-static method of a given class, and it can translate to a functional interface with the desired signature.
For example:
Points 8 and 9 of State of lambda give a rationale for this implementation.
From Overview of method references youtube video