这可能是一个微不足道的问题,但我还没有找到任何关于它的信息,所以这里有:
在实现
Comparable接口时,我们应该定义方法compareTo(),以便根据文档提供以下内容:
sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.
The relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
现在,令人困惑的部分是返回值,具体如下:
Returns a negative integer, zero, or a positive integer as this object
is less than, equal to, or greater than the specified object.
似乎大多数实现返回1,-1或0,即使它没有被提及作为要求以这种方式限制返回值.
因此,以下代码适用于对包含类Foo实例的列表(使用Collections.sort())进行排序:
public int compareTo(Foo other){
return this.value > other.value? 1 : this.value < other.value ? -1 : 0;
}
但是,这不是:
public int compareTo(Foo other){
return (int)(this.value - other.value);
}
其中value是long,并且值之间的差异不超过Integer.MAX_VALUE.
我在这里遗漏了什么,或者返回值是否恰好是1,-1或0,与文档相矛盾?
更新:感谢您的所有答案,但似乎人为因素归咎于此.我提到计算的差异小于Integer.MAX_VALUE,这应该意味着没有溢出,但我的计算是错误的,所以我确实得到了溢出,这导致了奇怪的结果.