I am currently learning lambda expressions on JDK 1.8. I have come across some code I have found that I do not understand.
Here is the code:
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.lang.Comparable;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws Exception
{
List<String> list = Arrays.asList("a", "b", "c");
sort(list, Comparable::<String>compareTo);
}
interface MyComparable {
public <T extends Comparable<T>> int compare(T obj1, T obj2 );
}
public static <T extends Comparable<T>> void sort(List<T> list, MyComparable comp) {
int n = comp.compare("5","2");
System.out.println(n);
}
}
comp.compare("5", "3")
eventually executes "5".compareTo("2")
.
My understanding was the compiler needs to find a static method with same signature as
public <T extends Comparable<T>> int compare(T obj1, T obj2 );
I have created such a method and it works. I do not understand why the java compiler calls "5".compareTo("2")
. Their method signitures are not the same.
Any information as to why the compiler generates this kind of code?