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?
InstanceMethodClass::testStr
has 3 arguments - the two arguments of the method -String str1,String str2
, and theInstanceMethodClass
instance for which it is called.Arrays.sort
expects aComparator<String>
, which requires a method with 2 String arguments.Your
InstanceMethodClass::testStr
doesn't match. If you changetestStr
to be static, you will get rid of theInstanceMethodClass
argument, and it should work.