“比较方法违反了它的一般约定!" [英] "Comparison method violates its general contract!"

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

问题描述

谁能简单解释一下,为什么这段代码会抛出异常比较方法违反了它的一般约定!",我该如何解决?

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;
}

推荐答案

您的比较器不可传递.

AB 的父级,BC 的父级.由于 A >BB >C,那么肯定是A >C.但是,如果在 AC 上调用比较器,它将返回零,这意味着 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天全站免登陆