【发布时间】:2013-01-02 16:12:16
【问题描述】:
试图理解以下输出:
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 实现。
【问题讨论】:
-
为什么要对时间戳减法进行排序?更具体地说,实现这一点的规范是什么?
-
java.sql.Timestamp实现了Comparable,因此有一个compareTo()方法。为什么不像return comm1.getDate().compareTo(comm2.getDate());那样直接委托给它呢? -
@BalusC 这是最好的方法,老实说,我不去想它就觉得很愚蠢。这就是我要做的。
-
不客气。看来彼得后来复制了这个答案,所以我不会转发它。
标签: java sorting comparator