Let's say that I have an array with objects, where I have some employees (objects). They all have: int age
, double salary
. I want to sort this array so my class implements Comparable <Employee>
. I've made a method:
public int compareTo(Employee other) {
return Double.compare(salary, other.salary);
}
And it's ok, sorting is working fine. But I'm sorting by double salary
. Now I want to sort by int age
so what now? I've made a method:
public int compareAge(Employee other) {
return Integer.compare(age, other.age);
}
And how can I use Arrays.sort()
with this? I want to have possibility to use both methods - sort by salary, sort by age. Thank you for help.
To implement multiple ways of sorting a collection of Employee
references, you should create separate classes implementing Comparator<Employee>
. So you might have:
public class EmployeeAgeComparator implements Comparator<Employee> {
...
}
public class EmployeeSalaryComparator implements Comparator<Employee> {
...
}
Then you just pass an instance of the appropriate comparator into the Arrays.sort
method.
Basically, implementing Comparable
is good when there's one sort order which is a sensible default - but comparators allow you to separate "the things being compared" from "the thing doing the comparing."
As a side-note, using double
to represent currency values (like salaries) is a bad idea, due to the way binary floating point works (e.g. not being able to represent 0.1 exactly)... use BigDecimal
, or store an integer number of cents (or whatever currency unit you're using).
See more on this question at Stackoverflow