gpt4 book ai didi

java - 按日期降序排序比较器未按预期工作

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:09 25 4
gpt4 key购买 nike

试图理解以下输出:

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

知道为什么底部的两个对象可能无法正确排序吗?我正在使用此时间戳的 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;

关于java - 按日期降序排序比较器未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14125298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com