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);
添加回答
举报