Why this lambda can be used here where expects a comparator in a Arrays.sort()

Viewed 59

I am new about Lambda, here is what the textbook (java in nutshell) says:

Only certain types are eligible to be the target of a lambda . Target types are also called functional interfaces and they must:

  • Be interfaces
  • Have only one nondefault method(but may have other methods that are default)

and the book gives me an example :

File dir =new File("/src");
String[] fileList =dir.list((d,fName)->fName.endWith(".java"))

I understand this lambda will convert into a FilenameFilter interface which is an @FunctionalInterface It does match the description in the book

enter image description here

However I can use lambda here to when the sort() is expecting to receive a Comparator

        int n =12;
        Function<String,String[]> f = (s) -> {
            String[] ans = new String[n];();
            for (int i = 0; i < n; i++) {
                ans[i] = s;
            }
            return ans;};
        Arrays.sort(f.apply("colin"),(String s1 ,String s2)->{
            return s1.length() - s2.length();});

I look over its source code to find Comparator is a @FunctionInterface enter image description here

but it have two nondefault methods compare and equals.It is different from what the book says.

1 Answers

equals is a public method of java.lang.Object. Those methods are explicitly not counted when identifying functional interfaces.

The real, autoritative definition of what a functional interface is (and what can therefore be "implemented" via a lambda) is found in the Java Langauge Specification.

Almost by necessity the definition of what a functional interface is in a guide book will be less strict and not as precise as the one in the Java Language Specification (because the later is written in a language that's not well-suited for initial learning of a concept and much better for creating multiple compatible implementations of the same thing).

See JLS §9.8 Functional Interfaces (emphasis mine):

For an interface I, let M be the set of abstract methods that are members of I that do not have the same signature as any public instance method of the class Object. [...]

Related