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.
You should use two
Comparator
classes instead of implementingComparable
.In short, a class that implements
Comparable
will be comparable in a single aspect to instances of that class.A class that implements
Comparator
will be a comparator medium for some other class. This means you can have multiple comparators to compare classes for different aspects. Furthermore, aComparator
class can be passed to a sort method, such asCollections.sort()
orArrays.sort()
, to allow precise control over the sort order and can also be used to control the order of certain data structures, such as sorted sets or sorted maps.To serve your purpose, what you could do is create two
Comparator
classes like:And then when calling a sorting method you pass in a
Comparator
you would like to use.For example, if you had an
ArrayList<Employee> list
and you want to sort it by salary you can do something like:Or if you had an
Employee[] array
and you want to sort it by age for example:To implement multiple ways of sorting a collection of
Employee
references, you should create separate classes implementingComparator<Employee>
. So you might have: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)... useBigDecimal
, or store an integer number of cents (or whatever currency unit you're using).