“比较方法违反了其一般合同!” [英] "Comparison method violates its general contract!"

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

问题描述

有人可以用简单的语言解释我,为什么这个代码会抛出异常,比较方法违反了它的一般合同!,我该如何修复它?

Can someone explain me in simple terms, why does this code throw an exception, "Comparison method violates its general contract!", and how do I fix it?

private int compareParents(Foo s1, Foo s2) {
    if (s1.getParent() == s2) return -1;
    if (s2.getParent() == s1) return 1;
    return 0;
}


推荐答案

你的比较器是不可传递。

A 成为 B的父

B C 的父级。由于 A> B B> C ,那么必须是 A>的情况。 ç。但是,如果在 A C 上调用比较器,它将返回零,这意味着 A == C 。这违反了合同,因此引发了异常。

Let A be the parent of B, and B be the parent of C. Since A > B and B > C, then it must be the case that A > C. However, if your comparator is invoked on A and C, it would return zero, meaning A == C. This violates the contract and hence throws the exception.

图书馆检测到这一点并让你知道,而不是表现不正常,这是相当不错的。

It's rather nice of the library to detect this and let you know, rather than behave erratically.

满足 compareParents()中的传递性要求的一种方法是遍历 getParent()链而不只是看着直接的祖先。

One way to satisfy the transitivity requirement in compareParents() is to traverse the getParent() chain instead of only looking at the immediate ancestor.

这篇关于“比较方法违反了其一般合同!”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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