Java Comparator.compare

本文详细介绍了Java Comparator接口的使用,包括比较两个对象的顺序、比较规则的性质(如对称性、传递性和一致性)以及如何确保比较器的正确实现。此外,还强调了当比较器的比较结果与equals方法不一致时应如何明确提示。
摘要由CSDN通过智能技术生成

Java Comparator.compare

Compares its two arguments for order. Returns a negatvie integer , zero , or a positive integer as the first argument is less than , equal to , or greater than the second.

比较两个参数的顺序。返回一个负数,零,正数,分别对应着 第一个参数 小于,等于,大于第二个参数。

In the foregoing description , the notation sgn(expressior) designates the mathematical signum funcion, which is defined to return one of -1,0,or 1 according to whether the value of expression in negative , zero or positive.

在前面的描述中,符号sgn(expressior)指定这个数学符号函数,该函数被定义为根据表达式的值是负的,零还是正数来返回-1,0,1;

The implementor must ensure that sgn(compare(x,y)) == -sgn(compare(y,x)) for all x and y. (This implies that compare(x,y) must throw an exception if and only if compare(y,x) throws an exception.)

实现这个接口是必须确保所有的x和y的sgn(compare(x,y))== -sgn(compare(y,x)) . 这也就意味着compare(x,y)必须要在且仅在compare(y,x)抛出异常时抛出异常。

The implementor must also ensure that the relation is transitive:((compare(x,y)>0)&&(compare(y,z)>0)) implies compare(x,z)>0.

实现这个接口也需要确保实现下面这个关系传递:((compare(x,y)>0)&&(compare(y,z)>0)) implies compare(x,z)>0.

Finally, the implementor must ensure the compare(x,y) == 0 implies that sgn(compare(x,z)) == sgn(compare(y,z)) for all z.

最后,实现者必须确保compare(x,y) == 0 也就意味着所有的z都要保证,(compare(x,z) == sgn(compare(y,z)))

It is generally the case, but not strictly required that (compare(x,y)0)(x.equals(y)).Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is “Note: this comparator imposes orderings that are inconsistent with equals”

一般是这样,但不是严格要求(compare(x,y)==0)=(x.equals(y))。一般来说,任何违反这个条件的比较器都应该清楚地指出这个事实。建议使用的语言是“注意:这个比较器强加的顺序与equals不一致”

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值