I am new in Java 8, went through few tutorials and docs. But couldn't get all the doubts cleared. While using sort operation of a list or collections class, we need(or not) to pass the comparator to get the desired sorting. but with Java 8, even we are passing any custom class which is not extending comparator, it's working fine. Below is my code :
public void compareList(List<Integer> list) {
CustomComparator comparator = new CustomComparator();
list.sort(comparator::dummyCompare);
Collections.sort(list, comparator::dummyCompare);
list.forEach(System.out::print);
}
custom comparator class :
class CustomComparator{
public int dummyCompare(final Integer a, final Integer b) {
return b.compareTo(a);
}
}
Now my doubt is, i see the list.sort/Collections.sort definitions which is something like this :
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
accepting Comparator as a second input, then why there is no error, please help or suggest me the link if it is already asked somewhere.
Thanks in advance !!
The question What is use of Functional Interface in Java 8? is different from the one I asked. It is discussing the functional interface and its uses with lambda and method-references. But my question is how come the type-check and method name 'dummyCompare' is getting ignored. Because in the sort function implementation of list or Collections, we are using Comparator's compare method.