gpt4 book ai didi

java - Java 8中 "functional interface"的精确定义

转载 作者:行者123 更新时间:2023-12-03 05:32:47 28 4
gpt4 key购买 nike

最近我开始探索 Java 8,但我不太理解 Java 实现 lambda 表达式所必需的“函数式接口(interface)”概念。有一个pretty comprehensive guide Java 中的 lambda 函数,但我陷入了 the chapter that gives definition to the concept of functional interfaces 。定义如下:

More precisely, a functional interface is defined as any interface that has exactly one abstract method.

然后他继续举例,其中一个是 Comparator 接口(interface):

public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}

我能够测试是否可以使用 lambda 函数代替 Comparator 参数,并且它可以工作(即 Collections.sort(list, (a, b) -> a-b))。

但是在 Comparator 接口(interface)中,compareequals 方法都是抽象的,这意味着它有两个抽象方法。那么,如果定义要求接口(interface)具有恰好一个抽象方法,那么这怎么行得通呢?我在这里缺少什么?

最佳答案

来自same page you linked to :

The interface Comparator is functional because although it declares two abstract methods, one of these—equals— has a signature corresponding to a public method in Object. Interfaces always declare abstract methods corresponding to the public methods of Object, but they usually do so implicitly. Whether implicitly or explicitly declared, such methods are excluded from the count.

我真的无法说得更好。

关于java - Java 8中 "functional interface"的精确定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14655913/

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