【问题标题】:Sorting an array of objects by certain variables within the array按数组中的某些变量对对象数组进行排序
【发布时间】:2017-04-15 01:26:10
【问题描述】:

我正在尝试为游戏建立高分。跑步是为此游戏制作的对象。 该类如下所示:

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

高分的数组长这样:

Run Highscoresaving[] = new Run[10];

现在我想对这个数组进行排序。最重要的价值是高等级,其次是低移动量,第三是短时间。如果运行达到相同的级别,则只需要移动,如果运行达到相同的级别并且具有相同的移动量,则只需要时间。

【问题讨论】:

标签: android arrays sorting


【解决方案1】:

你可以使用lambda expression:

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

为此,您必须像这样在对象中实现Comparable&lt;&gt;

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

希望对你有帮助

【讨论】:

  • 类Run调用必须声明为Abstract或在'comparable'中实现抽象方法'comparteTo(T)
  • @TimWalter 是的,你用了一个悲伤的名字。将你的对象重命名为 CustomRun 或其他东西。我用你的名字只是为了更容易理解
  • 名称没有问题。问题是我没有@override compareto
猜你喜欢
  • 2016-09-01
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
相关资源
最近更新 更多