java - 为什么 Double::compareTo 可以作为 Stream.max(Compa

Stream.max的api需要类型为 Comparator<? super T> 的参数,并为 Comparator ,唯一的抽象方法是

int compare(T o1, T o2)

但是 Double::compareTo , compareTo api是
public int compareTo(Double anotherDouble)

为什么只提供一个参数,为什么可以Double::compareTo用作 Stream 的参数
Optional<T> max(Comparator<? super T> comparator)

最佳答案

查看预言机 documentation .这是对 的引用实例方法。这意味着,它可以被认为是 BiFunction ,它将实例作为第一个参数。
在 Java Language Specification (15.13.3) 我们可以读到:

If the form is ReferenceType :: [TypeArguments] Identifier, the body of the invocation method similarly has the effect of a method invocation expression for a compile-time declaration which is the compile-time declaration of the method reference expression. Run-time evaluation of the method invocation expression is as specified in §15.12.4.3, §15.12.4.4, and §15.12.4.5, where:

  • The invocation mode is derived from the compile-time declaration as specified in §15.12.3.

  • If the compile-time declaration is an instance method, then the target reference is the first formal parameter of the invocation method. Otherwise, there is no target reference.

  • If the compile-time declaration is an instance method, then the arguments to the method invocation expression (if any) are the second and subsequent formal parameters of the invocation method. Otherwise, the arguments to the method invocation expression are the formal parameters of the invocation method.


有趣的部分是我加粗的。

关于java - 为什么 Double::compareTo 可以作为 Stream.max(Comparator<?super T>comparator) 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60240046/

相关文章:

java - 这个While 循环可以简化吗?

electron - 如何将在 Electron 上开发的桌面应用程序打包成.exe?

java - Java 中的静态方法调用是如何工作的?

prolog - Prolog数据库的Web访问

java - 如何将充满 if 语句的 for 循环更改为更优雅/高效的代码?

java - 在NIFI中创建自定义 Controller 服务时无法生成扩展的文档

java - 检查字符串中是否存在模式

r - 如何创建一个因子但保留基础值,而不仅仅是整数代码?

intellij-idea - IdeaVim:如何在不使用箭头键的情况下循环浏览列表项?

c - 我无法理解打印第一个八个数组元素的数组的输出