instance method reference. no suitable method found for

1.2k Views Asked by At

I introducing with new features of java 8.

I have following class:

class InstanceMethodClass {

    Integer testStr(String str1,String str2) {
        return str1.compareTo(str2);
    }
}

and following invocation:

 Arrays.sort(new String[]{"1", "3","2"},InstanceMethodClass::testStr );

After it I see following error:

java: no suitable method found for sort(java.lang.String[],InstanceMe[...]stStr)
    method java.util.Arrays.<T>sort(T[],java.util.Comparator<? super T>) is not applicable
      (cannot infer type-variable(s) T
        (argument mismatch; invalid method reference
          cannot find symbol
            symbol:   method testStr(T,T)
            location: class lambdas.staticReferences.InstanceMethodClass))
    method java.util.Arrays.<T>sort(T[],int,int,java.util.Comparator<? super T>) is not applicable
      (cannot infer type-variable(s) T
        (actual and formal argument lists differ in length))

Please explain what do I wrong?

2

There are 2 best solutions below

2
On BEST ANSWER

InstanceMethodClass::testStr has 3 arguments - the two arguments of the method - String str1,String str2, and the InstanceMethodClass instance for which it is called.

Arrays.sort expects a Comparator<String>, which requires a method with 2 String arguments.

Your InstanceMethodClass::testStr doesn't match. If you change testStr to be static, you will get rid of the InstanceMethodClass argument, and it should work.

0
On

It is working variant:

Arrays.sort(new String[]{"1", "3","2"}, new InstanceMethodClass()::testStr );