为什么我的简单比较器坏了? [英] Why is my simple comparator broken?
问题描述
我有一个课程,我已将其简化为:
I have a class, which I have simplified to this:
final class Thing {
private final int value;
public Thing(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override public String toString() {
return Integer.toString(value);
}
}
我想对这个东西的数组进行排序。所以我创建了一个简单的copmarator:
I want to sort an array of this thing. So I have created a simple copmarator:
private static final Comparator<Thing> reverse = new Comparator<Thing>() {
public int compare(Thing a, Thing b) {
return a.getValue() - b.getValue();
}
};
然后我使用 Arrays.sort的两个参数形式
。
这适用于我的测试用例,但有时它会以一个奇怪但可重复的顺序结束。
怎么会这样?
This works fine for my test cases, but sometimes it goes all wrong with the array ending up in a strange but repeatable order. How can this be?
推荐答案
整数溢出…或者更准确地说,是下溢。
Integer overflow… or more precisely, underflow.
相反,做一个明确的比较:
Instead, do an explicit comparison:
private static final Comparator<Thing> reverse = new Comparator<Thing>() {
public int compare(Thing a, Thing b) {
int av = a.getValue(), bv = b.getValue();
return (av == bv) ? 0 : ((av < bv) ? -1 : +1);
}
};
如果您确定差异不会环绕,则使用减法可以。例如,当有问题的数据被限制为非负数时。
Using subtraction is fine if you are sure that the difference won't "wrap around". For example, when the values in question are constrained to be non-negative.
这篇关于为什么我的简单比较器坏了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!