2015-06-20 92 views
3

我有一个雇员类有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用于自然排序,可以使用只有一个字段进行排序,比较器用于多个字段排序。但是如果我们看到我的例子,那么这两个接口都有能力做到这一点。所以,请解释一下这两个地方的独特功能,其中哪一个不能使用。

回答

0

有一些类,它们的性质指定一个顺序(如String s [字典顺序是事实上的标准]或Date s)。对于这些课程,您可以通过实施Comparable<T>来定义其自然顺序。但正如我将要描绘的,很多课程可以以多种方式进行排序。为此,Comparator<T>是非常有用的。

好吧,让我们看看其他一些例子。想象一下,你有一个Employee列表,你已经提到,你想做一些其他的东西。例如:您希望灵活地按名称或按收入或按出生日期对其进行排序或...(想象您想要选择如何订购它们)。对于这种情况,您可能需要指定要使用的确切Comparator,具体取决于您选择要排序的行。

另一个示例:Employee类已经存在,并且指定了某个顺序,但您对此顺序不满意。现在您可以简单地使用Comparator来指定您自己的订单,并获得您想要的行为。

2

使用可比如果要定义一个默认的(天然)排序问题的对象的行为,常见的做法是使用的技术或自然(数据库?)的对象标识符这一点。

使用比较器如果您要定义外部可控排序行为,则可以覆盖默认排序行为。您可以定义任意数量的订购行为,您可以根据需要使用这些行为。

0

如果你真的想知道两者的独特功能。

实现类比可让您将您的类与其他类进行比较。

Employee implements Comparable<Integer> 

比较器是比较同一类类型的两个实例的算法。

相关问题