我有一个雇员类有3个领域像下面。何时使用Comparator以及何时在Java中使用Comparable?
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个Employee对象,并添加到像下面这样的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用于自然排序,可以使用只有一个字段进行排序,比较器用于多个字段排序。但是如果我们看到我的例子,那么这两个接口都有能力做到这一点。所以,请解释一下这两个地方的独特功能,其中哪一个不能使用。