================================================================================
package examples;
/**
* Personクラス。
*/
public class Person {
private String name;
private int score;
public Person(String name, int score) {
this.name = name;
this.score = score;
}
/**
* 名前を返します。
*
* @return 名前を返します。
*/
public String getName() {
return name;
}
/**
* 名前をセットします。
*
* @param name 名前。
*/
public void setName(String name) {
this.name = name;
}
/**
* 得点を返します。
*
* @return 得点を返します。
*/
public int getScore() {
return score;
}
/**
* 得点を設定します。
*
* @param score 得点。
*/
public void setScore(int score) {
this.score = score;
}
public String toString() {
StringBuffer buffer = new StringBuffer(64);
buffer.append("[");
buffer.append("名前:");
buffer.append(name);
buffer.append(", ");
buffer.append("得点:");
buffer.append(score);
buffer.append("]");
return buffer.toString();
}
}
================================================================================
================================================================================
package examples;
import java.util.Comparator;
/**
* 得点を降順にソートするための比較関数を実装したクラス。
*/
public class DescendingScoreComparatorImpl implements Comparator {
public int compare(Object o1, Object o2) {
int ret;
if (o1 instanceof Person && o2 instanceof Person) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
if (p1.getScore() > p2.getScore()) {
ret = -1;
} else if (p1.getScore() < p2.getScore()) {
ret = 1;
} else {
ret = 0;
}
} else {
throw new ClassCastException("互いに型が一致しないため、相互比較することができません!");
}
return ret;
}
}
================================================================================
================================================================================
package examples;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* メインクラス。
*/
public class Main {
public static void main(String[] args) {
// リストの初期化。
List pList = new ArrayList();
pList.add(new Person("さとう", 54));
pList.add(new Person("たなか", 89));
pList.add(new Person("やまもと", 25));
pList.add(new Person("やまだ", 60));
pList.add(new Person("すずき", 98));
pList.add(new Person("かとう", 89));
// ソート前のリストの中身を標準出力する。
System.out.println("---- ソート前の一覧 ----");
System.out.println(pList);
// 得点の高い順にソートする。
Comparator comp = new DescendingScoreComparatorImpl();
Collections.sort(pList, comp);
// ソート後のリストの中身を標準出力する。
System.out.println("---- ソート後の一覧 ----");
System.out.println(pList);
}
}
================================================================================