什么是比较合同? [英] What is the compare contract?

查看:52
本文介绍了什么是比较合同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java代码引发了以下异常:

My java code threw the following exception:

java.lang.IllegalArgumentException: Comparison method violates its general contract!

我研究了StackOverflow上的消息,发现了几个问题,这些问题张贴了他们写得不好的比较方法,但是我想知道合同写在哪里,以及关于比较方法必须做什么的确切说明.

I researched the message on StackOverflow and found several questions that posted their poorly written compare methods, but I was wondering where the contract is written and what exactly does it state regarding what the compare method must do.

推荐答案

类似

实现者必须确保sgn(compare(x,y))==-sgn(compare(y,x))表示所有x和y.(这意味着,当且仅当compare(y,x)抛出一个异常时,compare(x,y)必须抛出一个异常.例外.)

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.)

实现者还必须确保该关系是可传递的:(((compare(x,y)> 0)&&(compare(y,z)> 0))表示compare(x,z)> 0.

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意味着所有z的sgn(compare(x,z))== sgn(compare(y,z)).

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

通常是这种情况,但不是严格要求(compare(x,y)== 0)==(x.equals(y)).一般来说,任何比较器违反此条件应清楚地表明这一事实.这推荐的语言是注意:此比较器强加了以下命令:与等式不一致."

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."

这篇关于什么是比较合同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆