Java - how to sort object in many ways: Arrays.sort(), Comparable<T>

北战南征 提交于 2019-12-01 17:53:47

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).

nem035

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<Employee> {
    int compare(Employee a, Employee b) {
        return Double.compare(a.salary, b.salary);
    }
}

class AgeComparator  implements Comparator<Employee> {
    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<Employee> list 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!