Thursday, October 17, 2013

Comparator as a Functional interface in Java 8

Comparator seemingly has two abstract methods but still has been tagged as a FunctionalInterface in Java 8. Consider the following:

@FunctionalInterface
public interface Comparator<T> {

    int compare(T o1, T o2);

    /**
     * ....
     * Note that it is <i>always</i> safe <i>not</i> to override
     * <tt>Object.equals(Object)</tt>.  However, overriding this method may,
     * in some cases, improve performance by allowing programs to determine
     * that two distinct comparators impose the same order.
     * ...
     */
    boolean equals(Object obj);
    
    ....

}

Based on a couple of references(included at the end) that I saw in StackOverflow, the reason apparently is just to document the additional benefits of overriding equals in classes implementing Comparator. So even though Comparator does have two abstract methods, only one of them is truly abstract thus satisfying the requirements of a Functional Interface.


References:

StackOverflow - Why does Comparator declare equals
Lambda FAQ has a small note on equals in Comparator.

No comments:

Post a Comment