Java快速開發平臺

          www.fastunit.com

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            23 Posts :: 0 Stories :: 273 Comments :: 0 Trackbacks

          當需要排序的集合或數組不是單純的數字型時,通常可以使用Comparator或Comparable,以簡單的方式實現對象排序或自定義排序。

          一、Comparator

          強行對某個對象collection進行整體排序的比較函數,可以將Comparator傳遞給Collections.sort或Arrays.sort。

          接口方法:

            /**
             * 
          @return o1小于、等于或大于o2,分別返回負整數、零或正整數。
             
          */
            
          int compare(Object o1, Object o2);

          案例:

          import java.util.Arrays;
          import java.util.Comparator;

          public class SampleComparator implements Comparator {

            
          public int compare(Object o1, Object o2) {
              
          return toInt(o1) - toInt(o2);
            }

            
          private int toInt(Object o) {
              String str 
          = (String) o;
              str 
          = str.replaceAll("""1");
              str 
          = str.replaceAll("""2");
              str 
          = str.replaceAll("""3");
              
          // 
              return Integer.parseInt(str);
            }

            
          /**
             * 測試方法
             
          */
            
          public static void main(String[] args) {
              String[] array 
          = new String[] { "一二""""" };
              Arrays.sort(array, 
          new SampleComparator());
              
          for (int i = 0; i < array.length; i++) {
                System.out.println(array[i]);
              }
            }

          }

           二、Comparable

          強行對實現它的每個類的對象進行整體排序,實現此接口的對象列表(和數組)可以通過Collections.sort或Arrays.sort進行自動排序。

          接口方法:

            /**
             * 
          @return 該對象小于、等于或大于指定對象o,分別返回負整數、零或正整數。 
             
          */
            
          int compareTo(Object o);

          假設對象User,需要按年齡排序:

          public class User {

            
          private String id;
            
          private int age;

            
          public User(String id, int age) {
              
          this.id = id;
              
          this.age = age;
            }

            
          public int getAge() {
              
          return age;
            }

            
          public void setAge(int age) {
              
          this.age = age;
            }

            
          public String getId() {
              
          return id;
            }

            
          public void setId(String id) {
              
          this.id = id;
            }

          }

          改造后的對象:

          import java.util.Arrays;

          public class User implements Comparable {

            
          private String id;
            
          private int age;

            
          public User(String id, int age) {
              
          this.id = id;
              
          this.age = age;
            }

            
          public int getAge() {
              
          return age;
            }

            
          public void setAge(int age) {
              
          this.age = age;
            }

            
          public String getId() {
              
          return id;
            }

            
          public void setId(String id) {
              
          this.id = id;
            }

            
          public int compareTo(Object o) {
              
          return this.age - ((User) o).getAge();
            }

            
          /**
             * 測試方法
             
          */
            
          public static void main(String[] args) {
              User[] users 
          = new User[] { new User("a"30), new User("b"20) };
              Arrays.sort(users);
              
          for (int i = 0; i < users.length; i++) {
                User user 
          = users[i];
                System.out.println(user.getId() 
          + " " + user.getAge());
              }
            }

          }


          三、Comparator和Comparable的區別

          先看一下使用Comparator對User集合實現排序的方式:

          import java.util.Arrays;
          import java.util.Comparator;

          public class UserComparator implements Comparator {

            
          public int compare(Object o1, Object o2) {
              
          return ((User) o1).getAge() - ((User) o2).getAge();
            }

            
          /**
             * 測試方法
             
          */
            
          public static void main(String[] args) {
              User[] users 
          = new User[] { new User("a"30), new User("b"20) };
              Arrays.sort(users, 
          new UserComparator());
              
          for (int i = 0; i < users.length; i++) {
                User user 
          = users[i];
                System.out.println(user.getId() 
          + " " + user.getAge());
              }
            }

          }

          一個類實現了Camparable接口則表明這個類的對象之間是可以相互比較的,這個類對象組成的集合就可以直接使用sort方法排序。
          Comparator可以看成一種算法的實現,將算法和數據分離,Comparator也可以在下面兩種環境下使用:
          1、類的設計師沒有考慮到比較問題而沒有實現Comparable,可以通過Comparator來實現排序而不必改變對象本身
          2、可以使用多種排序標準,比如升序、降序等

          posted on 2008-04-08 18:16 FastUnit 閱讀(47209) 評論(16)  編輯  收藏 所屬分類: Java

          Feedback

          # re: Comparator和Comparable在排序中的應用 2008-04-10 11:30 隔葉黃鶯
          博主還是沒有解釋一下,
          int compareTo(Object o);
          返回 負數、零、正數
          意味著什么?平白看去只不過是返回一個整數而已。  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2008-04-11 13:56 FastUnit
          接口方法的注釋中已經說明了,分別對應為小于、等于或大于指定對象。  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2008-04-12 10:48 豆抓搜索
          代碼寫的好..http://www.douzhua.com  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2008-04-12 12:53 隔葉黃鶯
          1 3 2
          3比1返回1意味著要做什么
          2比3返回-1又意味著要做什么  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2008-04-13 13:14 FastUnit
          3比1返回1,意味著3比1大,Comparator和Comparable的接口僅需比較出兩個對象的大小,排序的實現是由Collections.sort()和Arrays.sort()提供的。  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2008-04-24 00:35 隔葉黃鶯
          Collections.sort() 是調用了 Arrays.sort() 方法
          排序后的效果就是要保證 [i-1].compare([i]) <=0,就是在 [i-1].compare([i]) >0 時交換順序。

          換個角度理解就是他總是保持某種意義上的升序排列方式,讓前一個對象與后一個對象相比是小于零的(-1)  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2008-04-24 10:03 FastUnit
          @隔葉黃鶯
          是的,很贊同您探討問題的態度,了解Collections.sort和Arrays.sort可以更深入的理解Comparator和Comparable是如何應用的,很多時候直接看jdk源碼可以把事情看得更明白。  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2009-02-04 16:02 thebye85
          學習了。  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2009-02-18 09:28 greathjt
          好,學習了,寫的很清楚  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2009-09-15 19:36 11
          @隔葉黃鶯
            回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2010-06-29 17:33 淘寶網
          選擇默認值初始設置,然后繼續。  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2010-07-12 17:02 淘寶網女裝皇冠店
          強行對某個對象collection進行整體排序的比較函數,可以將Comparator傳遞給Collections.sort或Arrays.sort。

          接口方法:
            回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2011-08-03 17:49 啊啊啊啊啊啊啊啊啊啊啊
          很好
            回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2012-04-15 13:21 Morris
          thx, 學習了  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2012-09-09 09:49 mazheng3434027@sina.com
          感覺你對排序不懂。equal方法呢????你怎么沒覆蓋  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用[未登錄] 2013-05-07 10:43
          代碼我看懂了,那排序以后的結果在哪里輸出呢?  回復  更多評論
            

          主站蜘蛛池模板: 万荣县| 水城县| 临城县| 凉城县| 上杭县| 望谟县| 开封县| 龙里县| 浑源县| 友谊县| 德兴市| 全南县| 嫩江县| 抚顺县| 崇明县| 凉城县| 托克逊县| 凉山| 北流市| 扶余县| 临城县| 高要市| 馆陶县| 柞水县| 都江堰市| 华安县| 林芝县| 嘉荫县| 梅州市| 宜兰市| 东台市| 邓州市| 工布江达县| 大邑县| 琼中| 乌鲁木齐县| 惠东县| 潮安县| 中山市| 竹山县| 台前县|