如何按int降序对ArrayList排序?

时间:2018-09-29 13:36:45

标签: java sorting int reverse

我有以下代码按照我的Player类的等级对我的Player类进行排序。我的ArrayList类中有PlayerGame中的一个// Player class @Override public int compareTo(Player o) { return(this.getHowGood() > o.getHowGood() ? -1 : (this.getHowGood() == o.getHowGood() ? 0 : 1)); } ,我正在尝试按它们的评分高低进行排序。现在,它以相反的顺序排序(代码后的示例)。

PlayerSorter playerSorter = new PlayerSorter(allCompetitors);
ArrayList<Player> sortedPlayer = playerSorter.getSortedPlayerByHowGood();
System.out.println("-----Sorted JobCandidate by age: Ascending-----");
for(Player player : sortedPlayer) {
    System.out.println(player.getHowGood() + "");
}

游戏课

import java.util.ArrayList; 
import java.util.Collections;   

public class PlayerSorter {

    ArrayList<Player> players = new ArrayList<>();

    public PlayerSorter(ArrayList<Player> player) {
        this.players = player;
    }

    public ArrayList<Player> getSortedPlayerByHowGood() {         
        Collections.sort(players);
        return players;
    }
}

PlayerSorter类:

-----Sorted Player by rating: Ascending /*descending is what I'm looking for here*/-----
8
14
22
33
36
42
44
51
52
54
58
60
60
62
65
73
75
84
93
99

我在控制台中得到的内容(JFrame上的内容):

Player

正如我在上面显示的那样,数字在提高的过程中呈上升趋势,而我正试图与之相反,但无法弄清楚。我尝试将ArrayList类中的数字更改为相反的数字(负数),但这没有用。我尝试用Collections.reverse()颠倒col_1 != col_2的顺序,但这没用。

3 个答案:

答案 0 :(得分:1)

使用Collections.sort(players, Collections.reverseOrder())代替Collections.sort(players)

答案 1 :(得分:1)

排序后颠倒顺序:

Collections.sort(players);
Collections.reverse(players);

或一行:

Collections.sort(players, Collections.reverseOrder());

答案 2 :(得分:1)

替换

Collections.sort(players);

使用

Collections.sort(players,Collections.<Player>reverseOrder());