问题描述
以下Stream表达式完全正常:
The below Stream expression works perfectly fine:
Stream<String> s = Stream.of("yellow","blue", "white");
s.sorted(Comparator.reverseOrder())
.forEach(System.out::print);` //yellowwhiteblue
为什么带有方法引用的等效引用不能编译?
Why doesn't the equivalent one with method references compile?
s.sorted(Comparator::reverseOrder).forEach(System.out::print);
推荐答案
方法参考告诉Java将此方法视为单方法接口的实现 - 也就是说,方法引用应该具有签名 int foo(String,String)
,从而实现比较器< String>
。
A method reference is telling Java "treat this method as the implementation of a single-method interface"--that is, the method reference should have the signature int foo(String,String)
and thus implement Comparator<String>
.
Comparator.reverseOrder()
不 - 它返回一个比较器
实例。由于已排序
正在查找 比较器
,因此可以采用方法调用的结果,但它不能使用该方法作为接口实现。
Comparator.reverseOrder()
doesn't--it returns a Comparator
instance. Since sorted
is looking for a Comparator
, it can take the result of the method call, but it can't use that method as the interface implementation.
这篇关于为什么不排序(Comparator :: reverseOrder)有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!