我有这样的功能:
def getTime() : ArrayBuffer[Timestamp] = {
val offset = Timestamp.valueOf("2015-01-01 00:00:00").getTime()
val end = Timestamp.valueOf("2015-01-02 00:00:00").getTime()
val diff = end - offset + 1
val mList = ArrayBuffer[Timestamp]()
val numRecords = 3
var i = 0
while (i < numRecords) {
val rand = new Timestamp(offset + (Math.random() * diff).toLong)
mList += rand
i += 1
}
// mList.toList.sortWith(_ < _);
// scala.util.Sorting.quickSort(mList.toArray);
}
我试图对数组进行排序,但不能。我得到这个错误:
No implicit Ordering defined for java.sql.Timestamp.
我知道我需要定义如何排序会来完成。有没有一种方法可以轻松地在Java的排序是:Collections.sort(名单);或有使用Scala的一个更好的办法?
或者,在你的类的地方定义它,你是好去:
implicit def ordered: Ordering[Timestamp] = new Ordering[Timestamp] {
def compare(x: Timestamp, y: Timestamp): Int = x compareTo y
}
getTime().sorted // now this will work just fine
mList.sortWith(_.compareTo(_) < 1)
需要注意的是与一个匿名函数,你可以传递一个明确的功能,这将是这样的:
def comparator(first: Timestamp, second: Timestamp) = first.compareTo(second) < 1
mList.sortWith(comparator)
有时间戳的本身,在这里我们只是使用compareTo
方法排序没有隐含顺序。
由于@Nick用于指出排序上getTime()
在所有情况下没有suffient。我也看了,你会期望工作before
方法,但这只是用时代价值,以及比较。