简体   繁体   English

对数组的数组列表进行排序

[英]Sorting an Array List of Arrays

I'm reading game scores from a text file into an ArrayList. 我正在将游戏分数从文本文件读取到ArrayList中。 Each item in the ArrayList is a String array with 2 indexes, one stores the player's name and the other the score. ArrayList中的每个项目都是一个带有2个索引的String数组,一个存储玩家的名字,另一个存储得分。

What's the best way from here to sort the list into numerical order by the score, in order to display high scores? 为了显示高分,从这里按分数将列表按数字顺序排序的最佳方法是什么?

Thanks! 谢谢!

It should look something like this, assuming the score is stored in index 1: 假设得分存储在索引1中,它应该看起来像这样:

Collections.sort(playerList, new Comparator<String[]>(){
   @Override
   public int compare(String[] player1, String[] player2) {
         return Integer.parseInt(player1[1]) - Integer.parseInt(player2[1]);
     }
 }

playerList is the list of your arrays. playerList是阵列的列表。 This method will sort the array list for you using the supplied Comparator object which, as you see, takes two elements from the ArrayList and supplies a method of determining which one is first. 此方法将使用提供的Comparator对象为您对数组列表进行排序,如您所见,该对象从ArrayList中获取两个元素,并提供确定哪个是第一个的方法。

If you're not forced to use an array to store the score, then I recommend using a dedicated model class for it, that implements the Comparable interface. 如果您不被迫使用数组来存储分数,那么我建议为其使用专用的模型类,该类实现Comparable接口。

public class Score implements Comparable<Score> {
    final String name;
    final int score;

    public Score(String name, int score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public int compareTo(final Score that) {
        return that.score - this.score;
    }

    @Override
    public String toString() {
        return String.format("Score[name=%s, score=%d]", name, score);
    }
}

The current implementation sorts descending . 当前实现对descending排序。 If you want to sort ascending , then change it to return this.score - that.score; 如果要ascending排序,请更改它以return this.score - that.score; .

You can use that class like this: 您可以像这样使用该类:

public static void main(String[] args) {
    final List<Score> scores = new ArrayList<>();
    scores.add(new Score("Mike", 100));
    scores.add(new Score("Jenny", 250));
    scores.add(new Score("Gary", 75));
    scores.add(new Score("Nicole", 110));

    Collections.sort(scores);

    for (final Score score : scores) {
        System.out.println(score);
    }
}

The output will be: 输出将是:

Score[name=Jenny, score=250]
Score[name=Nicole, score=110]
Score[name=Mike, score=100]
Score[name=Gary, score=75]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM