This is not because your Employee
class already has a default ordering, that using Collections.sort
with a custom comparator will introduce a new layer of ordering.
For example let's say that the default ordering of your Employees
is by their salary in ascending order. Now let's say you want to sort them by salary in descending order.
According to your logic how this will behave?
Collections.sort(employees, new SalaryDescendingComparator());
The fact is that when you provide a custom comparator to Collections.sort
, it will use only this one and not the sorting mechanism that you implemented in your Employee
class.
As the doc states:
Sorts the specified list according to the order induced by the specified comparator.
So because the SalaryComparator
compares employees only by their salary, that's why you get this output.
If you want to sort by name first and then by salary, you'll have to do this in one time, i.e :
public class Employee implements Comparable<Employee> {
private int empSalary;
private String empName;
@Override
public int compareTo(Employee e) {
int cmp = this.empName.compareTo(e.empName);
return cmp != 0 ? cmp : Integer.compare(empSalary, e.empSalary);
}
}