0

Im trying to build a highscore for a game. A Run is an ojbect made for this game. The class looks like this:

public class Run {
    private int level;
    private int moves;
    private int time;}

The array of the highscore Looks like this:

Run Highscoresaving[] = new Run[10];

Now i would like to sort this array. The most important value is a high Level, second a low amount of moves and third a short amount of time. Moves are just needed if the run reached the same Level and time is just needed if the run reached the same Level and had the same amout of moves.

TimWalter
  • 47
  • 1
  • 12
  • 3
    Possible duplicate of [How to sort an array of objects in Java?](http://stackoverflow.com/questions/18895915/how-to-sort-an-array-of-objects-in-java) – Murat Karagöz Nov 30 '16 at 16:20

1 Answers1

0

You can use lambda expression:

List<Run> myRuns = //init
Collections.sort(myRuns, new RunComparator());

To do it you have to implement Comparable<> in your object like this:

public class Run implements Comparable<Run> {
  private int level;
  private int moves;
  private int time;
}
public class RunComparator implements Comparator<Run>{
  public int compare(Run o1, Run o2) {
    if(o1.getLevel() == o2.getLevel()){
      if(o1.getMoves() == o2.getMoves()){
        return o1.getTime() - o2.getTime();
      } 
      return o1.getMoves() - o2.getMoves();
    }
    return o1.getLevel() - o2.getLevel();
}

hope this helps

Pier Giorgio Misley
  • 5,305
  • 4
  • 27
  • 66
  • The class Run calls that is has to be declared Abstract or implement Abstract method 'comparteTo(T) in 'comparable' – TimWalter Nov 30 '16 at 16:43
  • @TimWalter yeah, you used a sad name for it.. Rename your object into CustomRun or something else.. I used your same name just to make it easier to understand – Pier Giorgio Misley Nov 30 '16 at 17:00
  • There isnt a problem with the Name. the problem is that i've got no @override compareto – TimWalter Nov 30 '16 at 18:31