If you're not forced to use an array to store the score, then I recommend using a dedicated model class for it, that implements the Comparable interface.
public class Score implements Comparable<Score> {
final String name;
final int score;
public Score(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public int compareTo(final Score that) {
return that.score - this.score;
}
@Override
public String toString() {
return String.format("Score[name=%s, score=%d]", name, score);
}
}
The current implementation sorts descending. If you want to sort ascending, then change it to return this.score - that.score;.
You can use that class like this:
public static void main(String[] args) {
final List<Score> scores = new ArrayList<>();
scores.add(new Score("Mike", 100));
scores.add(new Score("Jenny", 250));
scores.add(new Score("Gary", 75));
scores.add(new Score("Nicole", 110));
Collections.sort(scores);
for (final Score score : scores) {
System.out.println(score);
}
}
The output will be:
Score[name=Jenny, score=250]
Score[name=Nicole, score=110]
Score[name=Mike, score=100]
Score[name=Gary, score=75]
Collections.sort()and write your customcomparator.Collections.sortis well documented, as is the concept of using it in combination with aComparatorobject, simply search for them within the context of java and you'll find lots of tutorials that explain how to use them. Or search Stackoverflow for it, plenty of questions that involve using Collections.sort, too.