深入理解Arrays.sort()

來源:互聯網
上載者:User
翻譯人員: 鐵錨
翻譯日期: 2013年11月16日
原文連結:  Deep Understanding of Arrays.sort(T[], Comparator < ? super T > c)

Arrays.sort(T[], Comparator < ? super T > c) 方法用於對象數組按使用者自訂規則排序.
官方Java文檔只是簡要描述此方法的作用,並未進行詳細的介紹,本文將深入解析此方法。
1. 簡單樣本
sort方法的使用非常的簡單明了,下面的例子中,先定義一個比較Dog大小的Comparator,然後將其執行個體對象作為參數傳給sort方法,通過此樣本,你應該能夠快速掌握Arrays.sort()的使用方法。
[java]  view plain copy import java.util.Arrays;   import java.util.Comparator;       class Dog{       int size;          public Dog(int s){           size = s;       }   }       class DogSizeComparator implements Comparator<Dog>{           @Override       public int compare(Dog o1, Dog o2) {           return o1.size - o2.size;       }   }       public class ArraySort {           public static void main(String[] args) {           Dog d1 = new Dog(2);           Dog d2 = new Dog(1);           Dog d3 = new Dog(3);               Dog[] dogArray = {d1, d2, d3};           printDogs(dogArray);               Arrays.sort(dogArray, new DogSizeComparator());            printDogs(dogArray);       }           public static void printDogs(Dog[] dogs){           for(Dog d: dogs)               System.out.print(d.size + " " );               System.out.println();       }   }   輸出為:
[plain]  view plain copy 2 1 3   1 2 3  
2. 使用原則模式
這是策略模式( Strategy pattern )的一個完美又簡潔的樣本,值得一提的是為什麼這種情境下適合使用原則模式.
總體來說,策略模式允許在程式執行時選擇不同的演算法.比如在排序時,傳入不同的比較子(Comparator),就採用不同的演算法.
根據上面的例子,假設你想要根據Dog的重量來進行排序,可以像下面這樣,建立一個新的比較子來進行排序:
[java]  view plain copy class Dog{       int size;       int weight;      

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.