簡體   English   中英

對數組的數組列表進行排序

[英]Sorting an Array List of Arrays

我正在將游戲分數從文本文件讀取到ArrayList中。 ArrayList中的每個項目都是一個帶有2個索引的String數組,一個存儲玩家的名字,另一個存儲得分。

為了顯示高分,從這里按分數將列表按數字順序排序的最佳方法是什么?

謝謝!

假設得分存儲在索引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是陣列的列表。 此方法將使用提供的Comparator對象為您對數組列表進行排序,如您所見,該對象從ArrayList中獲取兩個元素,並提供確定哪個是第一個的方法。

如果您不被迫使用數組來存儲分數,那么我建議為其使用專用的模型類,該類實現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);
    }
}

當前實現對descending排序。 如果要ascending排序,請更改它以return this.score - that.score;

您可以像這樣使用該類:

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

輸出將是:

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