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

问题描述

我的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.

推荐答案

类似 Java文档 拥有

实现者还必须确保该关系是可传递的:(((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."

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

08-29 00:35