【问题标题】:Comparable and Comparator [duplicate]可比和比较器[重复]
【发布时间】:2012-03-15 13:06:37
【问题描述】:

可能重复:
Java: What is the difference between implementing Comparable and Comparator?
When to use Comparable vs Comparator

可比较接口和比较器接口有什么区别? 有人可以通过提供相应示例来解释我吗?

谢谢

【问题讨论】:

标签: java


【解决方案1】:

这是经验法则:

  1. 实现Comparable 接口以提供自然排序。
  2. 使用Comparator,根据您希望的标准对对象集合进行排序。

所以你有

注意:以下代码仅供参考,可能无法编译。

public class Student implements Comparable<Student>{

   public int age;
   public String name;

   //defined natural ordering is by name
   public int compareTo(Stundent that){
      return this.name.compareTo(that.name);
   }
}

public class AgeComparator implements Comparator<Student>{
   int compare(Student s, Student t){
      return s.age - t.age;
   }
}

现在,如果您有 Student 的列表,例如 studentList,您可以使用以下内容

Collections.sort(studentList); //sorts by natural ordering; by name
Collections.sort(studentList, new AgeComparator()); //sorts by age

【讨论】:

    【解决方案2】:

    来自Comparable上的 Java 文档

    此接口对实现它的每个类的对象进行总排序。这种排序称为类的自然排序,类的compareTo 方法称为其自然比较方法

    换句话说,实现Comparable 的类能够将自己与其他同类对象进行比较。

    来自Comparator上的 Java 文档

    一个比较函数,它将total ordering 强加于某些对象集合。比较器可以传递给排序方法(例如Collections.sortArrays.sort)以允许精确控制排序顺序。比较器还可用于控制某些数据结构的顺序(例如sorted setssorted maps),或为没有natural ordering 的对象集合提供排序。

    实现Comparator 的类能够相互比较其他对象。

    【讨论】:

      【解决方案3】:

      类型为Comparable&lt;T&gt; 的对象相对于T自然排序。给定一个T that,它确定thisthat 之间的关系(&lt;=&gt;)。

      Comparator&lt;T&gt;T排序。给定两个Ts,它确定它们的关系(&lt;=&gt;)。

      一个自然有序类型的例子是Integer。整数的自然顺序是 {-MAX_VALUE, ..., -1, 0, 1, ..., MAX_VALUE}。一个类型只能有一个自然顺序,部分原因是自然顺序的概念意味着它是唯一的,部分原因是单个类不能有Comperable.compareTo 的多个实现。

      另一方面,一个类型可以有多个有意义的Comparators。例如,String.CASE_INSENSITIVE_ORDER 是一个忽略大小写的Comparator&lt;String&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-05
        • 2014-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-26
        相关资源
        最近更新 更多