1 回答

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
創(chuàng)建一個(gè)類(lèi)來(lái)表示分?jǐn)?shù)/名稱(chēng)條目:
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 中。通過(guò)像這樣實(shí)現(xiàn) Comparable,您可以允許列表按分?jǐn)?shù)排序。
您可能還想在此類(lèi)中包含一個(gè)日期,以便較早日期取得的分?jǐn)?shù)排名高于具有相同分?jǐn)?shù)的其他條目。System.nanoTime()當(dāng)?shù)梅謺r(shí),您可以使用long 來(lái)獲取時(shí)間。
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);
}
}
編輯:如果您想通過(guò)其他方式排序,您需要一個(gè)自定義比較器。我根據(jù)這個(gè)答案改編了這個(gè),它考慮了大寫(xiě)。
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);
添加回答
舉報(bào)