Java之Comparable接口和Comparator接口

Comparable & Comparator 都是用来实现集合中元素的比较、排序的;

Comparable 是在集合内部定义的方法实现的排序;

Comparator 是在集合外部实现的排序;

所以,如想实现排序,就需要在集合外定义 Comparator 接口的方法或在集合内实现 Comparable 接口的方法。

Comparator位于包java.util下,而Comparable位于包java.lang下

Comparable 是一个对象本身就已经支持自比较所需要实现的接口(如 String、Integer 自己就可以完成比较大小操作,已经实现了Comparable接口)  

自定义的类要在加入list容器中后能够排序,可以实现Comparable接口,在用Collections类的sort方法排序时,如果不指定Comparator,那么就以自然顺序排序,如API所说:
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface
这里的自然顺序就是实现Comparable接口设定的排序方式。

Comparator 是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足你的要求时,你可以写一个比较器来完成两个对象之间大小的比较。
 
可以说一个是自已完成比较,一个是外部程序实现比较的差别而已。

比如:你想对整数采用绝对值大小来排序,Integer 是不符合要求的,你不需要去修改 Integer 类(实际上你也不能这么做)去改变它的排序行为,只要使用一个实现了 Comparator 接口的对象来实现控制它的排序就行了。

1 // AbsComparator.java
2 import java.util.*;
3 class AbsComparator implements Comparator {
4     public int compare(Object o1, Object o2) {
5         int v1 = Math.abs(((Integer) o1).intValue());
6         int v2 = Math.abs(((Integer) o2).intValue());
7         return v1 > v2 ? 1 : (v1 == v2 ? 0 : -1);
8     }
9 }
 1 // Test.java     
 2 import   java.util.*;     
 3 
 4 public   class   Test   {     
 5     public   static   void   main(String[]   args)   {     
 6     
 7       //产生一个20个随机整数的数组(有正有负)     
 8       Random   rnd   =   new   Random();     
 9       Integer[]   integers   =   new   Integer[20];     
10       for(int   i   =   0;   i   <   integers.length;   i++)     
11       integers[i]   =   new   Integer(rnd.nextInt(100)   *   (rnd.nextBoolean()   ?   1   :   -1));     
12     
13       System.out.println("用Integer内置方法排序:");     
14       Arrays.sort(integers);     
15       System.out.println(Arrays.asList(integers));     
16     
17       System.out.println("用AbsComparator排序:");     
18       Arrays.sort(integers,   new   AbsComparator());     
19       System.out.println(Arrays.asList(integers));     
20     }     
21 }

Collections.sort((List<T> list, Comparator<? super T> c)是用来对list排序的。

 如果不是调用sort方法,相要直接比较两个对象的大小,如下:
Comparator定义了俩个方法,分别是   int   compare(T   o1,   T   o2)和   boolean   equals(Object   obj),
用于比较两个Comparator是否相等
true only if the specified object is also a comparator and it imposes the same ordering as this comparator.
有时在实现Comparator接口时,并没有实现equals方法,可程序并没有报错,原因是实现该接口的类也是Object类的子类,而Object类已经实现了equals方法

 Comparable接口只提供了   int   compareTo(T   o)方法,也就是说假如我定义了一个Person类,这个类实现了   Comparable接口,那么当我实例化Person类的person1后,我想比较person1和一个现有的Person对象person2的大小时,我就可以这样来调用:person1.comparTo(person2),通过返回值就可以判断了;而此时如果你定义了一个   PersonComparator(实现了Comparator接口)的话,那你就可以这样:PersonComparator   comparator=   new   PersonComparator();
comparator.compare(person1,person2);。


原文地址:https://www.cnblogs.com/liyiran/p/4761737.html