Java快速開發(fā)平臺

          www.fastunit.com

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            23 Posts :: 0 Stories :: 273 Comments :: 0 Trackbacks

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

          一、Comparator

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

          接口方法:

            /**
             * 
          @return o1小于、等于或大于o2,分別返回負整數(shù)、零或正整數(shù)。
             
          */
            
          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

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

          接口方法:

            /**
             * 
          @return 該對象小于、等于或大于指定對象o,分別返回負整數(shù)、零或正整數(shù)。 
             
          */
            
          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的區(qū)別

          先看一下使用Comparator對User集合實現(xiàn)排序的方式:

          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());
              }
            }

          }

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

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

          Feedback

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

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

          # 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的接口僅需比較出兩個對象的大小,排序的實現(xiàn)是由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
          @隔葉黃鶯
          是的,很贊同您探討問題的態(tài)度,了解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 淘寶網(wǎng)
          選擇默認值初始設置,然后繼續(xù)。  回復  更多評論
            

          # re: Comparator和Comparable在排序中的應用 2010-07-12 17:02 淘寶網(wǎng)女裝皇冠店
          強行對某個對象collection進行整體排序的比較函數(shù),可以將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
          代碼我看懂了,那排序以后的結果在哪里輸出呢?  回復  更多評論
            

          主站蜘蛛池模板: 通渭县| 靖州| 壶关县| 延川县| 资中县| 平顺县| 石家庄市| 都兰县| 高安市| 汝南县| 深州市| 宝兴县| 家居| 肥乡县| 峨山| 呼图壁县| 洛扎县| 宣威市| 长沙县| 从化市| 五莲县| 江西省| 平泉县| 留坝县| 鄢陵县| 宝山区| 上犹县| 台前县| 临潭县| 南澳县| 东台市| 西青区| 资溪县| 金阳县| 吉安市| 利辛县| 耒阳市| 永善县| 民勤县| 固安县| 女性|