繁体   English   中英

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

[英]Sort by date descending comparator not working as expected

试图理解以下输出:

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

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

这是排序前的输出:

for (Communication n : retVal) {
    System.out.println(n.getDate().toString());
}

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

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实现。

最后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;

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

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

return Long.signum(t2 - t1);

您可以使用

return Long.compare(t2, t1);

但你最好比较日期。

return comm2.getDate().compareTo(comm1.getDate());

我的第一个想法是问题是溢出。 t1t2long s。 不同可能不适合int。

我会检查一下。

如果第二级比较对你来说足够好,你应该尝试:

return (int) ((t2 - t1)/1000);

这并不能保证不会出现溢出。 我至少会添加一个测试。

我认为最好的答案不是我的。 我最喜欢的是:

    if(t2 > t1)
        return 1;
    else if(t1 > t2)
        return -1;
    else
        return 0;

暂无
暂无

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

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