I am developing a game for android and I save the scores in a text file of the form “100&playername1,93&playername1,1950&playername2” etc. i.e. it is totally unordered.
Now I am trying to make a high score interface and I am aware that to sort the scores I should use String.split(",") followed by String.split("&")[0] to get the scores and put these in an ArrayList and then call Collections.compare(list). However once I have done that I then have no way of finding the names associated with the score.
Could anyone help me with this please. I have tried sorting the whole string in between brackets (putting the phrase “100&playername1” into the array, but that can’t sort according to orders of magnitude. By this I mean it would put 100 ahead of 1950.
Thanks for any help!
Make a class called
UsernameScorePair. Once you have split the scores and the usernames, put them in pairs (one for each “score&username”).For example, this class definition could work:
public class UsernameScorePair {
Make a class called
UsernameScorePairComparatorthat implementsComparator.In the
compare(Object o1, Object o2)method, cast the Objects to UsernameScorePairs and compare the scores. For example:Then use
Collections.sortlike this:Collections.sort(listofpairs, new UsernameScorePairComparator())I don’t remember if it sorts in ascending order or descending order. If it’s ascending order, then just change
return usp1.getScore() - usp2.getScore();toreturn usp2.getScore() - usp1.getScore();EDIT
A
Comparatorbasically compares two objects. In itscompareTomethod, it returns a negative value if the first is less than the second, a positive one if the first is greater than the second, and zero if they are both equal.You can implement a
Comparator(as I just did) to suit your needs. Then, using thatComparator, you can use standard API methods such asCollections.sort().I hope this works!