Java 8中功能接口的定义

参见英文答案 > Precise definition of “functional interface” in Java 8                                    6个
Java 8中功能接口的定义说:

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中的排序方法是:

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接口有两个抽象方法,它们是compare和equals,并用@FunctionalInterface注释.这是否违反了只有一个抽象方法的功能接口的定义?

确实,Comparator接口有两种抽象方法.但其中一个是equals,它会覆盖Object类中定义的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)的功能接口.

λ表达式(a,b) – > a> b? -1:1符合该合同:它声明2个参数并返回一个int.

翻译自:https://stackoverflow.com/questions/36844387/definition-of-functional-interface-in-java-8

转载注明原文:Java 8中功能接口的定义