问题
Ive got a highscore system for my game. and i want to be able to sort the numbers in acending order,ive got a way to sort the numbers
public static int[] sort(int[] a){
Arrays.sort(a);
return a;
}
but how do i make it so the scores stay with the name of the player that set it? for example me:10 you:50
You should be number 1 and me should be nubmer 2. how to i make it so that the string stays with the int when its sorted? thanks
回答1:
Easiest is to create a class to hold the person's name and score. Make it implement the Comparable interface, in the compareTo(...)
method compare the score of the current object, this
, to the object being passed into the method, and then sort an array of objects of this class just as you're doing.
class MyFoo implements Comparable<MyFoo> {
private String name;
private int score;
public MyFoo(String name, int score) {
// ... etc...
}
// getter methods here
public int compareTo(MyFoo other) {
return score - other.getScore();
}
//.... etc...
}
回答2:
Create a class Player
that contains both the name of the player and its score, and the appropriate getters (getName()
and getScore()
), and you'll be able to sort an array of Players with
Player[] players = ...
Arrays.sort(players, new Comparator<Player> {
public int compare(Player p1, Player p2) {
return Integer.valueOf(p1.getScore()).compareTo(p2.getScore());
}
}
来源:https://stackoverflow.com/questions/9143328/sorting-numbers-for-highscores-in-java