按日期降序比较器排序不按预期工作

map*_*aft 5 java sorting comparator

试图理解以下输出:

public class CommunicationComparator implements Comparator<Communication> {
    @Override
    public int compare(Communication comm1, Communication comm2) {
        long t1 = comm1.getDate().getTime();
        long t2 = comm2.getDate().getTime();
        return (int) (t2 - t1);
    }
}
Run Code Online (Sandbox Code Playgroud)

方法getDate()返回java.sql.Timestamp.

这是排序前的输出:

for (Communication n : retVal) {
    System.out.println(n.getDate().toString());
}
Run Code Online (Sandbox Code Playgroud)

2012-10-03 10:02:02.0
2012-10-07 03:02:01.0
2012-10-08 13:02:02.0
2012-10-09 03:02:00.0
2012-11-26 10:02:05.0
2012-11-28 11:28:11.0
2012-12-03 12:03:01.0
2012-12-06 15:03:01.0
2012-12-13 14:03:00.0
2012-12-28 11:03:00.0
2012-12-28 13:49:21.0

之后:

Collections.sort(retVal, new CommunicationsComparator());
Run Code Online (Sandbox Code Playgroud)

2012-12-13 14:03:00.0
2012-12-06 15:03:01.0
2012-12-03 12:03:01.0
2012-11-28 11:28:11.0
2012-10-09 03:02:00.0
2012-10-08 13:02:02.0
2012-11-26 10:02:05.0
2012-10-07 03:02:01.0
2012-10-03 10:02:02.0
2012-12-28 13:49:21.0
2012-12-28 11:03:00.0

任何想法为什么底部两个对象可能无法正确排序?我正在使用此Timestamp的MySQL JDBC实现.

Jam*_*inn 18

最后2个日期和早期日期之间的差异将溢出整数.

也许更好的解决方案是比较值,而不是减去它们.

    long t1 = comm1.getDate().getTime();
    long t2 = comm2.getDate().getTime();
    if(t2 > t1)
            return 1;
    else if(t1 > t2)
            return -1;
    else
            return 0;
Run Code Online (Sandbox Code Playgroud)


gog*_*ome 6

如果差异大于约25天,则发生溢出.(int不能表示更大的时间差,以毫秒为单位,大约为25天).这将使比较不正确.

这可以通过将return语句更改为:

return Long.signum(t2 - t1);
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 6

您可以使用

return Long.compare(t2, t1);
Run Code Online (Sandbox Code Playgroud)

但你最好比较日期.

return comm2.getDate().compareTo(comm1.getDate());
Run Code Online (Sandbox Code Playgroud)