当 Comparator 有两个抽象方法时,它如何成为功能接口?

How can Comparator be a Functional Interface when it has two abstract methods?

在Java8中,引入了@FunctionalInterface注解来表示任何只有一个抽象方法的接口为函数式接口。引入它的原因之一是向用户(程序员)表明 lambda 表达式可以在功能接口的上下文中使用。

Comparator 接口用@FunctionalInterface 注释。但是,两个方法是抽象的。

int compare(T o1, T o2);

boolean equals(Object obj);

FunctionalInterface的文档中,明确提到

Conceptually, a functional interface has exactly one abstract method.

这里的equals方法不是抽象的吗?

文档还指出:

If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

并且由于equals是其中一种方法,接口的"abstract method count"仍然是1。

也来自the FunctionalInterface documentation page:

If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere. [emphasis mine]

因为 equalsObject 的 public 方法,所以此声明适用;因此,对于 Comparator 只有 compare 方法有助于抽象方法计数。

适用此规则的其他值得注意的方法是 toString and hashCode