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 arr
You should use two Comparator
classes instead of implementing Comparable
.
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, a Comparator
class can be passed to a sort method, such as Collections.sort()
or Arrays.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:
class SalaryComparator implements Comparator {
int compare(Employee a, Employee b) {
return Double.compare(a.salary, b.salary);
}
}
class AgeComparator implements Comparator {
int compare(Employee a, Employee b) {
return Integer.compare(a.age, b.age);
}
}
And then when calling a sorting method you pass in a Comparator
you would like to use.
For example, if you had an ArrayList
and you want to sort it by salary you can do something like:
Collections.sort(list, new SalaryComparator()); // sort the list by salaries
Or if you had an Employee[] array
and you want to sort it by age for example:
Arrays.sort(array, new AgeComparator()); // sort the array by age