[JAVA]有關比較器(Comparator接口)的用法及對象數組排序問題

跟上篇文章一樣,今天討論的對象也是Arrays.sort()方法與Comparator接口的相互用法。

當你想對一個普通的對象數組排序,怎麼辦?

這時候你應該想到的是,使用Comparator接口和Arrays.sort()結合使用。

Comparator也叫作比較器,用法在代碼中體現。

首先,寫一個比較器類。

import java.util.Comparator;  

public class StudentComparator implements Comparator<Student>{  
    public int compare(Student o1, Student o2) {  
        //當然可以用其他成員變量來作爲衡量比較的標準 
        return o1.getNumber().compareTo(o2.getNumber());  
    }  
}  

現在,我創建了一個普通的學生類Student。存入數據:

import java.util.Arrays;  
public class Test {  
    public static void main(String[] args) {      
        Student sc = new Student("10000", "lz", 18);  
        Student sc1 = new Student("10001", "wx", 18);  
        Student sc2 = new Student("10003", "zh", 18);  
        Student sc3 = new Student("10002", "gd", 18);  
        Student scs[] = new Student[]{sc,sc1,sc2,sc3};  
        Arrays.sort(scs, new StudentComparator());//這裏傳出了一個比較器  
        for (int i = 0; i < scs.length; i++) {  
            System.out.println(scs[i].getNumber()+","+scs[i].getName()+","+scs[i].getAge());  
        }  
    }  
}  

看到Arrays.sort()裏除了傳遞一個數組進去外,還有一個比較器。
這樣就可以實現,對任何對象數組進行排序操作了。

但是值得注意的一點是,如果你Arrays.sort()方法中沒傳一個比較器的話,會拋出java.lang.ClassCastException異常。這點值得注意。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章