[英]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());
我的第一個想法是問題是溢出。 t1
和t2
是long
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.