Comparable和Comparator

來源:互聯網
上載者:User
          Comparable & Comparator 都是用來實現集合中的排序的,只是 Comparable 是在集合內部定義的方法實現的排序,Comparator 是在集合外部實現的排序,所以,如想實現排序,就需要在集合外定義 Comparator 介面的方法或在集合內實現 Comparable 介面的方法。

  Comparable 是一個對象本身就已經支援自比較所需要實現的介面(如 String、Integer 自己就可以完成比較大小操作)

  而 Comparator 是一個專用的比較子,當這個對象不支援自比較或者自比較函數不能滿足你的要求時,你可以寫一個比較子來完成兩個對象之間大小的比較。

  可以說一個是自已完成比較,一個是外部程式實現比較的差別而已。

  用 Comparator 是策略模式(strategy design pattern),就是不改變對象自身,而用一個策略對象(strategy object)來改變它的行為。

  比如:你想對整數採用絕對值大小來排序,Integer 是不符合要求的,你不需要去修改 Integer 類(實際上你也不能這麼做)去改變它的排序行為,只要使用一個實現了 Comparator 介面的對象來實現控制它的排序就行了。

       

  1. // AbsComparator.java   
  2. import  java.util.*;
  3. public  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. }

可以用下面這個類測試 AbsComparator:

  1. // Test.java
  2. import  java.util.*;
  3.   public  class  Test  {
  4.   public  static  void  main(String[]  args)  {
  5.   //產生一個20個隨機整數的數組(有正有負)
  6.    Random  rnd  =  new  Random();
  7.    Integer[]  integers  =  new  Integer[20];
  8.    for(int  i  =  0;  i  <  integers.length;  i++)
  9.    integers[i]  =  new  Integer(rnd.nextInt(100)  *  (rnd.nextBoolean()  ?  1  :  -1));
  10.   system.out.println("用Integer內建方法排序:");
  11.    Arrays.sort(integers);
  12.    system.out.println(Arrays.asList(integers));
  13.   system.out.println("用AbsComparator排序:");
  14.    Arrays.sort(integers,  new  AbsComparator());
  15.    system.out.println(Arrays.asList(integers));
  16.   }
  17. }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.