Java 8 stream max() function argument type Comparator vs Comparable

前端 未结 4 1851
陌清茗
陌清茗 2021-01-01 16:41

I wrote some simple code like below. This class works fine without any errors.

public class Test {
    public static void main(String[] args) {
        List&         


        
4条回答
  •  误落风尘
    2021-01-01 17:02

    First trick: all instance methods actually take 1 additional implicit argument, the one you refer to as this in method body. E.g.:

    public final class Integer extends Number implements Comparable {
        public int compareTo(/* Integer this, */ Integer anotherInteger) {
            return compare(this.value, anotherInteger.value);
        }
    }
    
    Integer a = 10, b = 100;
    int compareResult            = a.compareTo(b);
    // this actually 'compiles' to Integer#compareTo(this = a, anotherInteger = b)
    

    Second trick: Java compiler can "transform" the signature of a method reference to some functional interface, if the number and types of arguments (including this) satisfy:

    interface MyInterface {
        int foo(Integer bar, Integer baz);
    }
    
    Integer a = 100, b = 1000;
    
    int result1 =                   ((Comparator) Integer::compareTo).compare(a, b);
    int result2 = ((BiFunction) Integer::compareTo).apply(a, b);
    int result3 =                           ((MyInterface) Integer::compareTo).foo(a, b);
    
    // result1 == result2 == result3
    

    As you can see class Integer implements none of Comparator, BiFunction or a random MyInterface, but that doesn't stop you from casting the Integer::compareTo method reference as those interfaces.

提交回复
热议问题