the next snippet taken from this java tutorial, compares the second argument object to the first one rather than viceversa. *The method hireDate() returns a Date object signifying the hiring date of that particular employee.
import java.util.*;
public class EmpSort {
static final Comparator<Employee> SENIORITY_ORDER =
new Comparator<Employee>() {
public int compare(Employee e1, Employee e2) {
return e2.hireDate().compareTo(e1.hireDate());
}
};
Here is the java tutorial explanation:
Note that the Comparator passes the hire date of its second argument to its first rather than vice versa. The reason is that the employee who was hired most recently is the least senior; sorting in the order of hire date would put the list in reverse seniority order.
Still I do not get why by inverting e1 and e2 in compareTo
it should solve the issue.
Any further clarification?
Thanks in advance.
If you want to change the sort order then use:
Collections.sort(list, Collections.reverseOrder(comparator));
Don't play with the Comparator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With