Java 8如何知道在排序时使用哪个String :: compareTo方法引用? [英] How does Java 8 know which String::compareTo method reference to use when sorting?
问题描述
Java如何知道在调用 Collections.sort(someListOfStrings,String :: compareTo)时使用哪个
? String :: compareTo
方法引用; compareTo
不是静态的,它需要知道比较左手边的值
。
How does Java know which String::compareTo
method reference to use when calling Collections.sort(someListOfStrings, String::compareTo);
? compareTo
is not static and it needs to know the value
of the "left hand side" of the comparison.
推荐答案
假设您使用 Comparator
接口的方法参考:
Suppose that you use method reference for Comparator
interface:
Comparator<String> cmp = String::compareTo;
当你拨打 cmp.compare(左,右)时
(这是单一抽象方法或比较器
接口的SAM),出现了魔术:
When you call the cmp.compare(left, right)
(which is "single abstract method" or "SAM" of Comparator
interface), the magic occurs:
int result = cmp.compare(left, right);
| |
/------------------------/ |
| /---------------/
| |
left.compareTo(right);
基本上SAM的所有参数都转换为引用方法的参数,但此
对象(位于左侧)也计为参数。
Basically all the parameters of SAM are converted to the parameters of the referred method, but this
object (which is on the left side) is also counted as parameter.
这篇关于Java 8如何知道在排序时使用哪个String :: compareTo方法引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!