1 回答

TA貢獻1825條經驗 獲得超4個贊
創建一個類來表示分數/名稱條目:
public class ScoreEntry implements Comparable<ScoreEntry> {
public final String name;
public final int score;
public ScoreEntry (String name, int score){
this.name = name;
this.score = score;
}
public int compareTo (ScoreEntry other){
return Integer.signum(score - other.score);
}
}
然后你可以將它們放入 ArrayList 中。通過像這樣實現 Comparable,您可以允許列表按分數排序。
您可能還想在此類中包含一個日期,以便較早日期取得的分數排名高于具有相同分數的其他條目。System.nanoTime()當得分時,您可以使用long 來獲取時間。
public class ScoreEntry implements Comparable<ScoreEntry> {
public final String name;
public final int score;
public final long time;
public ScoreEntry (String name, int score, long time){
this.name = name;
this.score = score;
this.time = time;
}
public int compareTo (ScoreEntry other){
if (score == other.score)
return Long.signum(other.time - time);
return Integer.signum(score - other.score);
}
}
編輯:如果您想通過其他方式排序,您需要一個自定義比較器。我根據這個答案改編了這個,它考慮了大寫。
Comparator<ScoreEntry> nameComparator = new Comparator<>(){
public int compare(ScoreEntry first, ScoreEntry second) {
int res = String.CASE_INSENSITIVE_ORDER.compare(first.name, second.name);
if (res == 0)
res = first.name.compareTo(second.name);
return res;
}
}
然后你將其傳遞給排序方法:
Collections.sort(scoresList, nameComparator);
添加回答
舉報