gpt4 book ai didi

java - 为什么 Double::compareTo 可以作为 Stream.max(Comparatorcomparator) 的参数

转载 作者:行者123 更新时间:2023-12-01 12:27:05 27 4
gpt4 key购买 nike

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/

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