比较方法违反了Java 7中的一般合同 [英] Comparison Method violates its general contract in Java 7
问题描述
我在Java 7中编译了一些Java代码,然后运行它后,得到了比较方法违反了它的一般合同。
I am getting a "Comparison Method violates its general contract" after compiling some Java code in Java 7, and then running it.
我读过比较方法违反了其总合同!仅限Java 7,并意识到我的代码在以前版本的Java中被忽略了。但是,我无法弄清楚我的代码有什么问题。 Collections.sort()生成错误。
I have read Comparison method violates its general contract! Java 7 only and realize that there is something wrong with my code that was ignored in previous versions of Java. However I cannot work out what is wrong with my code. The Collections.sort() generates the error.
我的代码是:
public Comparator sortBySmoothDays() {
Comparator c = new Comparator() {
public int compare(Object arg0, Object arg1) {
Date date0 = ((PosObject)arg0).getDate();
Date date1 = ((PosObject)arg1).getDate();
double d1 = MyUtils.calcSmoothDays(date0, new Date());
double d2 = MyUtils.calcSmoothDays(date1, new Date());
if (d1 >= d2) {
return 1;
}
else {
return -1;
}
}
};
return c;
}
Comparator c = ComparatorUtils.getInstance().sortBySmoothDays();
Collections.sort(posList, c);
任何人都可以提供帮助吗?谢谢!
Can anyone help? Thank you!
推荐答案
如果值相等,比较器必须返回0。在当前的实现中,如果它们相等则返回1。正确比较 double
值的最简单方法是调用 Double.compare
:
A comparator must return 0 if the values are equal. In your current implementation, you return 1 if they are equal. The easiest way to compare your double
values correctly is to call Double.compare
:
double d1 = MyUtils.calcSmoothDays(date0, new Date());
double d2 = MyUtils.calcSmoothDays(date1, new Date());
return Double.compare(d1, d2);
这篇关于比较方法违反了Java 7中的一般合同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!