======================================================
1、Arrays.sort(int[] a)
這種形式是對一個數組的所有元素進行排序,並且是按從小到大的順序。
舉例如下(點“+”可查看代碼):

import java.util.Arrays; publicclassMain {4publicstaticvoid main(String[] args) { int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5}; Arrays.sort(a); for(int i = 0; i < a.length; i ++) { System.out.print(a[i] + " "); } } }
運行結果如下:
0 1 2 3 4 5 6 7 8 9
---------------------------------------------------------
2、Arrays.sort(int[] a, int fromIndex, int toIndex)
這種形式是對數組部分排序,也就是對數組a的下標從fromIndex到toIndex-1的元素排序,注意:下標為toIndex的元素不參與排序哦!
舉例如下(點“+”可查看代碼):

import java.util.Arrays; publicclassMain {4publicstaticvoid main(String[] args) { int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5}; Arrays.sort(a, 0, 3);//3是指0位置開始后包括零位置 后的三個8for(int i = 0; i < a.length; i ++) { System.out.print(a[i] + " "); } } }
View Code
運行結果如下:
7 8 9 2 3 4 1 0 6 5
上例只是把 9 8 7排列成了7 8 9
----------------------------------------------------------
3、public static <T> void sort(T[] a,int fromIndex, int toIndex, Comparator<? super T> c)
上面有一個拘束,就是排列順序只能是從小到大,如果我們要從大到小,就要使用這種方式
這里牽扯到了Java里面的泛型,如果讀者不是很了解,可以暫時不去管它,如果真的很想了解,建議查閱上面我推薦的那本書,上面有詳細的介紹。
讀者只需要讀懂下面的例子就可以了,其實就是多了一個Comparator類型的參數而已。

package test; import java.util.Arrays; import java.util.Comparator; publicclassMain {publicstaticvoid main(String[] args) { //注意,要想改變默認的排列順序,不能使用基本類型(int,double, char)//而要使用它們對應的類 Integer[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5}; //定義一個自定義類MyComparator的對象 Comparator cmp = new MyComparator(); Arrays.sort(a, cmp); for(int i = 0; i < a.length; i ++) { System.out.print(a[i] + " "); } } } //Comparator是一個接口,所以這里我們自己定義的類MyComparator要implents該接口//而不是extends Comparator class MyComparator implements Comparator<Integer>{ @Overridepublicint compare(Integer o1, Integer o2) { //如果n1小於n2,我們就返回正值,如果n1大於n2我們就返回負值,//這樣顛倒一下,就可以實現反向排序了if(o1 < o2) { return1; }elseif(o1 > o2) { return -1; }else { return0; } } }