Java - 如何以多种方式对对象进行排序:Arrays.sort(),Comparable< T> [英] Java - how to sort object in many ways: Arrays.sort(), Comparable<T>
问题描述
假设我有一个包含对象的数组,我有一些员工(对象)。它们都有: int age
,双倍薪水
。我想对这个数组进行排序,以便我的类实现 Comparable< Employee>
。我做了一个方法:
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);
}
没关系,排序工作正常。但我按双薪
排序。现在我想按 int age
排序那么现在呢?我做了一个方法:
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);
}
我怎样才能使用 Arrays.sort()
有这个吗?我希望有可能使用这两种方法 - 按工资排序,按年龄排序。感谢您的帮助。
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.
推荐答案
实现多种方式对 Employee $ c的集合进行排序$ c>引用,你应该创建单独的类来实现
Comparator< Employee>
。所以你可能有:
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> {
...
}
然后你只需传递一个实例适当的比较器进入 Arrays.sort
方法。
Then you just pass an instance of the appropriate comparator into the Arrays.sort
method.
基本上,实现可比较$当有一个明确的默认排序时,c $ c>是好的 - 但是比较器允许你将被比较的东西与进行比较的东西分开。
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."
作为旁注,使用 double
来表示货币值(如工资)是一个坏主意,因为二进制浮点的工作方式(例如不能准确地表示0.1)...使用 BigDecimal
,或者存储整数分数(或者你正在使用的任何货币单位)。
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).
这篇关于Java - 如何以多种方式对对象进行排序:Arrays.sort(),Comparable< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!