compare(T o1, T o2)
方法:
实施者必须确保
sgn(compare(x, y)) == -sgn(compare(y, x))
x
和
y
. (这意味着
compare(x, y)
必须抛出异常当且仅当
compare(y, x)
实施者还必须确保关系是可传递的:
((compare(x, y)>0) && (compare(y, z)>0))
compare(x, z)>0
.
最后,实施者必须确保
compare(x, y)==0
意味着
sgn(compare(x, z))==sgn(compare(y, z))
对于所有z。
那么,你违反了这三条规则中的哪一条?
全部3个
违反第一条规则是因为
time
long
所以
(int) (lhs.mTaskInfo.time - rhs.mTaskInfo.time)
可以等于
Integer.MIN_VALUE
. 如果将这两个参数翻转为
compare()
整数最小值
,因为
int
违反第二条规则是因为
整数
时间
长的
,我假设它们包含标准毫秒值,并且
24天
. 假设输入是
Jan 1, Jan 15, Jan 30
.
compare(Jan 1, Jan 15)
compare(Jan 15, Jan 30)
compare(Jan 1, Jan 30)
应该是+29天,但溢出的返回时间大约是-19天。哎呀!!!!
null, Jan 1, Jan 2
.
compare(null, Jan 1)
compare(null, Jan 2)
但是
compare(Jan 1, Jan 2)
是+1天。
解决方案
这个
溢流和
MIN_VALUE
问题可以通过使用
Long.compare(long x, long y)
.
对于
null
public int compare(DownloadTask lhs, DownloadTask rhs) {
if (lhs == null) {
if (rhs == null)
return 0;
return -1;
}
if (rhs == null)
return 1;
return Long.compare(lhs.mTaskInfo.time, rhs.mTaskInfo.time);
}
public int compare(DownloadTask lhs, DownloadTask rhs) {
return (lhs == null ? (rhs == null ? 0 : -1)
: (rhs == null ? 1 : Long.compare(lhs.mTaskInfo.time, rhs.mTaskInfo.time)));
}