The Stream
class in Java 8 defines a max
method that requires a Comparator
argument. Here is the method signature:
Optional<T> max(Comparator<? super T> comparator)
Comparator
is a functional interface that has an abstract compare
method with this signature. Notice compare
requires 2 arguments.
int compare(T o1, T o2)
The Comparable
interface has an abstract compareTo
method with this signature. Notice compareTo
requires only 1 argument.
int compareTo(T o)
In Java 8, the following code works perfectly. However, I expected a compilation error like, "the Integer class does not define compareTo(Integer, Integer)".
int max = Stream.of(0, 4, 1, 5).max(Integer::compareTo).get();
Can someone help explain why it's possible to pass an instance of Comparable
to a method that expects an instance of Comparator
even though their method signatures are not compatible?