Collections.sort() と Comparator
比較方法を指定して,Collections.sort()を使う方法.
久々に使うと忘れるので,メモっとく.
/**
* 学生をあらわすクラス
*/
class Student {
private int ID; //学籍番号
private String name; //氏名
private int score; //成績(以下コンストラクタやらGetter / Setterやら…)
}class StudentManager {
・・・
public List sortStudents(ArrayList students){
・・・
Collections.sort(students, new StudentScoreComparator())
return students;
}
}/**
* 生徒を成績順(降順)にソートする方法の定義
*/
class StudentScoreComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
return - (((Student)obj1).getScore() - ((Student)obj2).getScore());
}
}