Why can a lambda expression be used as a Comparator?

后端 未结 9 1932
渐次进展
渐次进展 2020-12-16 02:55

In the book OCP Study Guide there is this example about a Comparator that can be initialized in two ways. The first is via an anonymous class like this:

<         


        
9条回答
  •  -上瘾入骨i
    2020-12-16 03:21

    If you read the documentation of the Comparator interface, you can read:

    Functional Interface: This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

    The Comparator interface is thus implemented like:

    @FunctionalInterface
    public interface Comparator {
    
        int compare(T o1, T o2);
    
        // ...
    
    }

    Now if we look at the documentation of @FunctionalInterface we see:

    An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. 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.

    So basically if you have an interface with one abstract method, and you annotate the interface as a @FunctionalInterface, then that interface is a target for functions: in that you more or less construct an anonymous class that implements the functional interface and the function you specify is the implementation of the only abstract method.

    In other words, the expression:

    Comparator byWeight = 
    

    is equivalent to:

    Comparator byWeight = new Comparator(){
        public int compare(Duck d1, Duck d2){
            return (d1,d2);
        }
    }
    

提交回复
热议问题