class Employee
{
private int empId;
private String empName;
private int empAge;
public Employee(int empId, String empName, int empAge) {
this.empId = empId;
this.empName = empName;
this.empAge = empAge;
}
// setters and getters
我想按照员工姓名(empName)进行排序,如果有多个员工的姓名相同,则按照员工ID(empId)进行排序。
为此,我编写了一个使用java.util.Comparator的自定义比较器,如下所示。
class SortByName implements Comparator<Employee>
{
public int compare(Employee o1, Employee o2) {
int result = o1.getName().compareTo(o2.getName());
if (0 == result) {
return o1.getEmpId()-o2.getEmpId();
} else {
return result;
}
}
}
我创建了8个员工对象,并像下面这样添加到一个ArrayList中。
List<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee(3, "Viktor", 28));
empList.add(new Employee(5, "Viktor", 28));
empList.add(new Employee(1, "Mike", 19));
empList.add(new Employee(7, "Mike", 19));
empList.add(new Employee(4, "Mark", 34));
empList.add(new Employee(6, "Jay", 34));
empList.add(new Employee(8, "Gayle", 10));
empList.add(new Employee(2, "Gayle", 10));
并使用上述比较器对列表进行排序,结果如下所示。
Collections.sort(empList,new SortByName());
它一直运行得非常好。但是这也可以使用Comparable来完成,如下所示。
class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
this.empId = empId;
this.name = name;
this.age = age;
}
//setters and getters
@Override
public int compareTo(Employee o) {
int result = this.getName().compareTo(o.getName());
if (0 == result) {
return this.getEmpId()-o.getEmpId();
} else {
return result;
}
}
}
使用Collections.sort(empList)对列表进行排序;
所以我想知道这两者的用例或者它们究竟在哪里使用?我理解Comparable用于自然排序,只能使用一个字段进行排序,而comparator用于多个字段排序。但是如果我们看到我的示例,这两个接口都具有执行这两个操作的能力。因此,请解释一下这两个接口的独特功能,其中另一个无法使用的功能。