0

我有一个对象数组,这些对象都存储了多个值。我将它们放在一个对象数组中。

class PlayerScores {

String playerName;
   int pos=0;
   int played=0;
   int win=0;
   int draw=0;
   int lose=0;
   int goalsFor=0;
   int goalsAgainst=0;
   int goalDifference=0;
   int points=0;

   public PlayerScores() {
   }
}

这些存储在数组中:

Player Scores[] playersObjects = new PlayerScores[int];

            playersObjects[i] = new PlayerScores();

我想搜索'playersObject []'然后在一个新的对象数组中排序,其中最高点首先在数组中,其余的按降序排列。我不确定如何对对象中的单个值进行排序。

任何帮助将不胜感激,

谢谢。

4

2 回答 2

6

您可以使用Arrays.Sort并提供自定义Comparator. 像这样的东西应该工作:

public class PlayerScoresComparator implements Comparator<PlayerScores> {
    @Override
    public int compare(PlayerScores lhs, PlayerScores rhs) {
        return lhs.points - rhs.points;
    }
}
于 2013-01-09T22:58:59.453 回答
1

作为 kabuko 建议的替代方案,您可以使用 PlayerScore 对象的ArrayList,同时实现Comparable接口并向 PlayerScore 类添加 compareTo(PlayerScore another) 方法,如下所示:

public class PlayerScores implements Comparable<PlayerScores> {
  [...]

public int compareTo(PlayerScore another) {
  //example of a method to calculate which ogject is "greater".
  //See Comparable documentation for details. You will need to implement proper logic
  return getHighScore() - another.getHighScore(); 
}

然后您将能够通过 Collections.sort() 对 ArrayList 进行排序:

ArrayList<PlayerScores> scores = new ArrayList<PlayerScores>();
[...] //Populate scores list
Collections.sort(scores)

如果您无论如何都必须使用 ArrayList,例如,如果您要将它附加到 ListView,这将很有用。

于 2013-01-09T23:28:25.770 回答