java comparable_Java Comparable返回值,它必须是1,-1还是0?

这可能是一个微不足道的问题,但我还没有找到任何关于它的信息,所以这里有:

在实现

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,这应该意味着没有溢出,但我的计算是错误的,所以我确实得到了溢出,这导致了奇怪的结果.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值