Definition of Functional Interface in Java 8 [duplicate]

醉酒当歌 提交于 2019-12-22 05:14:00

问题


The definition of a functional Interface in Java 8 says:

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.

So how come we have this:

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

As the sort method in List is:

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);
        }
    }

And the lambda expression says:

Lambda Expression should be assignable to a Functional Interface

The Comparator interface has two abstract methods which are compare and equals and is annotated with @FunctionalInterface. Does not this violate the definition of a functional interface having only one abstract method?


回答1:


It is true that the Comparator interface has 2 abstract methods. But one of them is equals, which overrides the equals method defined in the Object class, and this method doesn't count.

From @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.

As such, this makes the Comparator interface a functional interface where the functional method is compare(o1, o2).

The lambda expression (a, b) -> a > b ? -1 : 1 complies with that contract: it declares 2 parameters and return an int.



来源:https://stackoverflow.com/questions/36844387/definition-of-functional-interface-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!