Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering by date. Comparator. Java

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.

like image 209
Rollerball Avatar asked Dec 05 '22 11:12

Rollerball


1 Answers

If you want to change the sort order then use:

Collections.sort(list, Collections.reverseOrder(comparator));

Don't play with the Comparator.

like image 194
camickr Avatar answered Dec 28 '22 18:12

camickr