Java记录 -69- Comparable与Comparator的区别

来源:互联网 发布:mysql float 转换int 编辑:程序博客网 时间:2024/06/05 07:09

Comparable & Comparator 都是用来实现集合中元素的比较、排序的,只是 Comparable 是在集合内部定义的方法实现的排序Comparator 是在集合外部实现的排序,所以,如想实现排序,就需要在集合外定义 Comparator 接口的方法或在集合内实现 Comparable 接口的方法。
可以说一个是自已完成比较,一个是外部程序实现比较的差别而已。
Comparator位于包java.util下,而Comparable位于包java.lang下。

Comparable

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

而 Comparator 是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足你的要求时,你可以写一个比较器来完成两个对象之间大小的比较
用 Comparator 是策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。
比如:你想对整数采用绝对值大小来排序,Integer 是不符合要求的,你不需要去修改 Integer 类(实际上你也不能这么做)去改变它的排序行为,只要使用一个实现了 Comparator 接口的对象来实现控制它的排序就行了。

public class AbsComparator   implements   Comparator   {         public int   compare(Object   o1,   Object   o2)   {           int   v1   =   Math.abs(((Integer)o1).intValue());           int   v2   =   Math.abs(((Integer)o2).intValue());           return   v1   >   v2   ?   1   :   (v1   ==   v2   ?   0   :   -1);         }     }public   class   Test   {         public   static   void   main(String[]   args)   {               //产生一个20个随机整数的数组(有正有负)           Random   rnd   =   new   Random();           Integer[]   integers   =   new   Integer[20];           for(int   i   =   0;   i   <   integers.length;   i++)           integers[i] = new  Integer(rnd.nextInt(100)  *  (rnd.nextBoolean() ? 1 :  -1));               System.out.println("用Integer内置方法排序:");           Arrays.sort(integers);           System.out.println(Arrays.asList(integers));               System.out.println("用AbsComparator排序:");           Arrays.sort(integers,   new   AbsComparator());           System.out.println(Arrays.asList(integers));         }     }

Comparator和Comparable提供方法:

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)方法。

Comparator和Comparable使用:

假如我定义了一个Person类;

当Person类实现了Comparable接口,那么实例化Person类的person1后,想比较person1和一个现有的Person对象person2的大小时,我就可以这样来调用,通过返回值就可以判断了

person1.comparTo(person2);

而当定义了一个PersonComparator(实现了Comparator接口)的话,那你就可以这样:

PersonComparator   comparator=   new   PersonComparator();
comparator.compare(person1,person2);