gpt4 book ai didi

java - 什么是比较契约(Contract)?

转载 作者:行者123 更新时间:2023-12-03 23:05:31 26 4
gpt4 key购买 nike

我的 java 代码抛出以下异常:

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

我研究了 StackOverflow 上的消息,发现了几个发布了他们写得不好的比较方法的问题,但我想知道契约(Contract)是在哪里写的,以及关于比较方法必须做什么,它到底说明了什么。

最佳答案

看起来像Java Doc拥有它

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

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

Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all 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."

关于java - 什么是比较契约(Contract)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15765158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com