gpt4 book ai didi

java-8 - 流 : "cannot convert Comparator to int" when using method reference

转载 作者:行者123 更新时间:2023-12-05 00:14:55 24 4
gpt4 key购买 nike

假设我有一个字符串流:

Stream<String> stream = Stream.of("c","a","b");

这工作正常:
stream.sorted(Comparator.reverseOrder())

但使用替代语法不会:
stream.sorted(Comparator::reverseOrder)
^
Bad return type in method reference: cannot convert Comparator<T> to int

当我在 IDE 中按 Ctrl+左键单击时,两者都会将我带到相同的静态方法,返回 Comparator 中的比较器类(class):
  public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {
return Collections.reverseOrder();
}

一本书解释说:

Comparator is a functional interface. This means that we can use method references or lambdas to implement it. The Comparator interface implements one method that takes two String parameters and returns an int . However, Comparator::reverseOrder doesn’t do that. It is a reference to a function that takes zero parameters and returns a Comparator . This is not compatible with the interface. This means that we have to use a method and not a method reference.



但我不明白。

最佳答案

方法引用等价于 Lambda 表达式,只能在 FunctionalInterface 处使用。是期待。 sorted不期望 FunctionalInterface ,它期望一个普通的,'ol Comparator .如果sorted的签名如下,方法引用会起作用:<T> sorted(Supplier<? extends Comparator<T>> s) .

关于java-8 - 流 : "cannot convert Comparator to int" when using method reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45700795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com