我正在使用treeMap创建一个评分系统,我想只显示前3个结果。
当玩家输入第4个结果(如果它大于当前最小值)时,如何删除最小值并将其替换为新值。
到目前为止,我的代码对分数进行了排序:
Map<Integer, String> treeMap = new TreeMap<Integer, String>(new MyCopr());
treeMap.put(name1val, name1);
treeMap.put(name2val, name2);
treeMap.put(name3val, name3);
treeMap.put(tempval, tempname);
for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
playername1.append("Key : " + entry.getKey() + " Value : "
+ entry.getValue() + "\n");
}
}
class MyCopr implements Comparator<Integer> {
@Override
public int compare(Integer lhs, Integer rhs) {
return rhs.compareTo(lhs);
}
}
从这里我可以做些什么来取代最小的值?感谢。
答案 0 :(得分:3)
我会使用一组分数(像这样) -
private static int MAX_SCORES = 3;
private SortedSet<Score> scores = new TreeSet<Score>();
public Set<Score> getScores() {
return scores;
}
public void addScore(String name, int score) {
scores.add(new Score(name, score));
while (scores.size() > MAX_SCORES) {
scores.remove(scores.first());
}
}
private class Score implements Comparable<Score> {
private String name;
private int score;
private Score(String name, int score) {
this.name = name;
this.score = score;
}
public int compareTo(Score obj) {
if (this == obj) {
return 0;
}
if (this.score < obj.score) {
return -1;
} else if (this.score > obj.score) {
return 1;
}
return name.compareTo(obj.name);
}
public String toString() {
return name + " - score = " + score;
}
}
然后像这样使用它......
System.out.println(obj.getScores());
obj.addScore("Player 1", 1);
obj.addScore("Player 2", 2);
obj.addScore("Player 3", 3);
System.out.println(obj.getScores());
obj.addScore("Player 4", 4);
System.out.println(obj.getScores());
产生这个(当我运行它时) -
[]
[Player 1 - score = 1, Player 2 - score = 2, Player 3 - score = 3]
[Player 2 - score = 2, Player 3 - score = 3, Player 4 - score = 4]