[JAVA]有關Java中Arrays.sort()的用法

平常,作爲靜態類Arrays中的靜態方法sort()經常被我們使用。但是你知道怎麼控制它排序按照正序還是逆序呢?

其實,可以通過使用Comparable接口//Comparator接口,實現compareTo() / /compare()方法來調整正序還是逆序。

代碼如下:

首先創建一個StudentCoparable類使用Comparable接口,並實現方法compareTo();

public class StudentComparable implements Comparable<StudentComparable>{  
    private String number;  
    private String name;  
    private int age;  

    public int compareTo(StudentComparable student) {  
            return Integer.parseInt(this.number)-Integer.parseInt(student.number);  
    }  

然後我們開始測試數據,

import java.util.Arrays;  
public class Test {  
    public static void main(String[] args) {  
        StudentComparable sc = new StudentComparable("10000", "lz", 18);  
        StudentComparable sc1 = new StudentComparable("10001", "wx", 18);  
        StudentComparable sc2 = new StudentComparable("10003", "zh", 18);  
        StudentComparable sc3 = new StudentComparable("10002", "gd", 18);  
        StudentComparable scs[] = new StudentComparable[]{sc,sc1,sc2,sc3};  
        Arrays.sort(scs);//正序排序  
        for (int i = 0; i < scs.length; i++) {  
            System.out.println(scs[i].getNumber()+","+scs[i].getName()+","+scs[i].getAge());  
        }  
    }  
}  

此時,測試結果爲:
可見是正序排序。

那如果想要逆序排序呢?其實很簡單,只需要把compareTo中的

return Integer.parseInt(this.number)-Integer.parseInt(student.number);  

//換個位置

return Integer.parseInt(student.number)-Integer.parseInt(this.number); 

即可變爲逆序排序。

其中,Comparator接口也是相同,只需修改compare中的返回值,就可以調整正逆序輸出了!!

結論:Arrays中的sort()方法,是跟Comparable接口,Comparator接口有密切相關,如果將來想使用這兩個接口和Arrays.sort()方法,值得注意一下。

發佈了30 篇原創文章 · 獲贊 129 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章