简体   繁体   English

在Java中对整数进行排序会首先返回负数吗?

[英]Sorting ints in java returns negative numbers first?

I have a comparator like so: 我有一个类似的比较器:

Collections.sort( sortedPlayers, new Comparator<RoundPlayer>()
{
    public int compare(RoundPlayer p1, RoundPlayer p2)
    {
        return p1.getScore() - p2.getScore();
    }
});

Sorted players is a list of player objects, the scores they return are ints such as, 200, -300, 1000 etc. 排序的玩家是玩家对象的列表,它们返回的分数是整数,例如200,-300、1000等。

The goal of the comparator is to sort them so they are descending order, 1000, 200, -300. 比较器的目标是对它们进行排序,使它们以降序排列,即1000、200,-300。

However this comparator seems to return erratic results. 但是,此比较器似乎返回了不稳定的结果。 Often with negative numbers coming out first. 通常会先出现负数。

Just reverse your return value you currently have 只需反转您当前的退货价值

sample 样品

return p2.getScore() - p1.getScore(); //will sort in descending order

If you want to sort by descending order then consider wrapping your Comparator using Collections.reverseOrder(Comparator cmp) . 如果要按降序排序,请考虑使用Collections.reverseOrder(Comparator cmp)包装Comparator器。

Also note that subtracting the two values is a bad idea because of integer overflow. 另请注意,由于整数溢出,将两个值相减是个坏主意。 Your compare logic is p1.getScore() - p2.getScore() . 您的compare逻辑是p1.getScore() - p2.getScore() Consider p1.score = 2147483647, p2.score = -2147483648, your comparator would return -1, incorrectly indicating p1's score is less than p2's score. 考虑p1.score = 2147483647,p2.score = -2147483648,您的比较器将返回-1,错误地表明p1的分数小于 p2的分数。

The correct logic is to test for <, = and >, returning -1, 0 and 1. Better yet, Integer already implements this logic so you can simply delegate to its compareTo method. 正确的逻辑是测试<,=和>,返回-1、0和1。更好的是, Integer已经实现了此逻辑,因此您可以简单地委派给它的compareTo方法。

return Integer.valueOf(p1.getScore()).compareTo(Integer.valueOf(p2.getScore());

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

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