I would use a set of scores (like this) -
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;
}
}
And then use it like so ...
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());
Which yields this (when I run it) -
[]
[Player 1 - score = 1, Player 2 - score = 2, Player 3 - score = 3]
[Player 2 - score = 2, Player 3 - score = 3, Player 4 - score = 4]