通过数组中的某些变量对对象数组进行排序

时间:2016-11-30 16:18:55

标签: android arrays sorting

我试图为游戏建立一个高分。 A Run是为这个游戏制作的ojbect。 该课程如下:

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

高分的数组看起来像这样:

Run Highscoresaving[] = new Run[10];

现在我想对这个数组进行排序。最重要的值是高水平,第二个是低移动量,第三个是短时间。如果跑步达到相同的水平,则只需要移动,如果跑步达到相同的水平并且具有相同的移动量,则仅需要时间。

1 个答案:

答案 0 :(得分:0)

您可以使用lambda expression

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

要做到这一点,你必须在你的对象中实现Comparable<>,如下所示:

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();
}

希望这会有所帮助