简体   繁体   English

何时使用Comparator以及何时在Java中使用Comparable?

[英]When to use Comparator and when to use Comparable in Java?

I have an Employee class which has 3 fields like below. 我有一个Employee类,它有3个字段,如下所示。

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

For this I want to sort based on Employee Name(empName), if multiple employees have the same name, then sort based on employee id(empId). 为此,我想基于员工姓名(empName)进行排序,如果多个员工具有相同的名称,则根据员工ID(empId)进行排序。

For this I have written a custom comparator using java.util.Comparator like below. 为此,我使用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;
    }
   }
  }

I have created 8 Employee objects and added to an ArrayList like below. 我创建了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));          

And sorted the list like below using the above comparator. 并使用上面的比较器对列表进行了如下排序。

Collections.sort(empList,new SortByName());

It has worked absolutely fine. 它工作得非常好。 But this can be done using Comparable also like below. 但这可以使用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;
    }

}

}

Sort the list using Collections.sort(empList); 使用Collections.sort(empList)对列表进行排序;

So I want to know what is the use case or where exactly we use these both? 所以我想知道用例是什么或者我们究竟在哪里使用它们? I understood that Comparable is used for natural sorting and can sort using only one field and comparator is used for multiple fields sorting. 我知道Comparable用于自然排序,只能使用一个字段排序,比较器用于多个字段排序。 But if we see my example both the interfaces has the capability to do these both. 但是如果我们看到我的例子,那么接口都有能力做到这两点。 So please explain me what are the unique features of these both where other one can't be used. 所以请解释一下这两者的独特功能,其中一个不能使用。

Use Comparable if you want to define a default (natural) ordering behavior of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this. 如果要定义相关对象的默认(自然)排序行为,请使用Comparable ,通常的做法是使用对象的技术或自然(数据库?)标识符。

Use Comparator if you want to define an external controllable ordering behavior, this can override the default ordering behavior. 如果要定义外部可控排序行为,请使用Comparator ,这可以覆盖默认排序行为。 You can define any number of ordering behavior, which you can use as required. 您可以定义任意数量的排序行为,您可以根据需要使用这些行为。

There are classes, which specify an order by their nature (like String s [lexicographic order is de-facto standard] or Date s). 有一些类,它们按性质指定一个顺序(如String s [字典顺序是事实标准]或Date s)。 For this classes, you can define their natural order by implementing Comparable<T> . 对于这个类,您可以通过实现Comparable<T>来定义它们的自然顺序。 But as I will sketch, a lot of classes can be orderd in more than one way. 但正如我将要草绘的那样,很多课程可以通过多种方式进行排序。 For this, Comparator<T> is extremely useful. 为此, Comparator<T>非常有用。

Ok, so let us look at some other example. 好的,让我们看看其他一些例子。 Imagine you have a list of Employee as you have mentioned and you want to do some other stuff. 想象一下,如上所述,您有一份Employee列表,并且您想要做其他一些事情。 For example: you want the flexibility to sort them by name OR by income OR by birth date OR... (imagine you want to choose how to order them). 例如:您希望能够灵活地按名称或按收入或出生日期对它们进行排序或...(想象您想选择如何订购它们)。 For this case, you may want to specify the exact Comparator to use, depending on the row you selected to sort after. 对于这种情况,您可能希望指定要使用的精确Comparator ,具体取决于您选择要排序的行。

Another example: The Employee class is already there and does specify some order, but you are unsatisfied with this order. 另一个例子: Employee类已经存在并指定了一些订单,但您对此订单不满意。 Now you can simply specify your own order with an Comparator and get the behaviour YOU desire. 现在,您只需使用Comparator指定自己的订单,即可获得您想要的行为。

If you really want to know the unique feature of both. 如果你真的想知道两者的独特功能。

Implementing Comparable let you compare your Class to an other Class. 通过实现Comparable,您可以将Class与其他Class进行比较。

Employee implements Comparable<Integer>

A Comparator is an algorithm to compare two instances of a same Class type. 比较器是一种比较同一类类型的两个实例的算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM