:: (double colon) operator in Java 8

前端 未结 17 3474
旧时难觅i
旧时难觅i 2020-11-21 11:10

I was exploring the Java 8 source and found this particular part of code very surprising:

//defined in IntPipeline.java
@Override
public fin         


        
17条回答
  •  天命终不由人
    2020-11-21 11:48

    This is a method reference in Java 8. The oracle documentation is here.

    As stated in the documentation...

    The method reference Person::compareByAge is a reference to a static method.

    The following is an example of a reference to an instance method of a particular object:

    class ComparisonProvider {
        public int compareByName(Person a, Person b) {
            return a.getName().compareTo(b.getName());
        }
    
        public int compareByAge(Person a, Person b) {
            return a.getBirthday().compareTo(b.getBirthday());
        }
    }
    
    ComparisonProvider myComparisonProvider = new ComparisonProvider();
    Arrays.sort(rosterAsArray, myComparisonProvider::compareByName); 
    

    The method reference myComparisonProvider::compareByName invokes the method compareByName that is part of the object myComparisonProvider. The JRE infers the method type arguments, which in this case are (Person, Person).

提交回复
热议问题