我有一個僱員類有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用於自然排序,可以使用只有一個字段進行排序,比較器用於多個字段排序。但是如果我們看到我的例子,那麼這兩個接口都有能力做到這一點。所以,請解釋一下這兩個地方的獨特功能,其中哪一個不能使用。