2016-11-06 23 views
0

排序分高分,ArrayList的我如何通過積分排序我的ArrayList「highscoreList」(由高到低)如何在Java中

這裏是高分

public class Highscore { 
    private String name; 
    private int points; 
    private Date date; 

這裏我列出

ArrayList<Highscore> highscoreList; 
+1

使用匿名比較器的Collections.sort –

回答

0

你必須使用Collections.sort()並覆蓋其compare()方法:

Collections.sort(highscoreList, new Comparator<>() { 
    @Override 
    public int compare(Highscore h1,Highscore h2) { 
     return h2.getPoints() - h1.getPoints(); 
    } 
}); 

compare()方法的身體說如何Highscore類的實例會進行比較。假設points是主要和唯一標準,請將其與getter一起使用。

自從您使用h2.getPoints() - h1.getPoints()以來,這種排序方式降序排列。要實現升序,只需將compare()方法的主體更改爲:h1.getPoints() - h2.getPoints()

0

Collections.sort方法具有可選Comparator變量:

Collections.sort(highscoreList, new Comparator<Highscore>(){ 
        public int compare(Highscore h1,Highscore h2){ 
          // Write your logic here. 
        }}); 

當然,你可以寫一個實現比較器的實際類,上面只是簡寫。

+0

如果您在「Comparator」實現中添加了return語句會更有幫助 – peter