Java8中函数式接口的定义

Definition of Functional Interface in Java 8

Java8 中功能接口的定义说:

A functional interface is defined as any interface that has exactly one explicitly declared abstract method. (The qualification is necessary because an interface may have non-abstract default methods.) This is why functional interfaces used to be called Single Abstract Method (SAM) interfaces, a term that is still sometimes seen.

那我们怎么会有这个:

List<Double> temperature = 
   new ArrayList<Double>(Arrays.asList(new Double[] { 20.0, 22.0, 22.5 }));
temperature.sort((a, b) -> a > b ? -1 : 1);

因为List中的sort方法是:

default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }

而 lambda 表达式表示:

Lambda Expression should be assignable to a Functional Interface

Comparator接口有两个抽象方法compareequals,注解为@FunctionalInterface。这不违反函数式接口只有一个抽象方法的定义吗?

确实Comparator接口有2个抽象方法。但是其中一个是equals,它覆盖了Objectclass中定义的equals方法,这个方法不算。

来自 @FunctionalInterface:

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.

因此,这使得 Comparator 接口成为功能接口,其中功能方法是 compare(o1, o2)

lambda 表达式 (a, b) -> a > b ? -1 : 1 符合该约定:它声明了 2 个参数和 return 一个 int.