java.lang.IllegalArgumentException:比较方法违反其一般合同 [英] java.lang.IllegalArgumentException: Comparison method violates its general contract

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

问题描述

以下是我的比较器的比较方法。我不知道是什么问题。我查找了其他类似的标题问题和答案堆栈溢出,但不知道什么是我的方法,但我不断得到java.lang.IllegalArgumentException:比较方法违反了它的一般合同!

Hi below is my compare method of my comparator. I am not sure what is wrong. I looked up other similar titled questions and answers on stack overflow but not sure what is wrong with my method but I keep getting java.lang.IllegalArgumentException: Comparison method violates its general contract!

任何帮助将非常感谢。

public int compare(Node o1, Node o2)
{
    HashMap<Integer,Integer> childMap = orderMap.get(parentID);
    if(childMap != null && childMap.containsKey(o1.getID()) && 
                           childMap.containsKey(o2.getID()))
    {
        int order1 = childMap.get(o1.getID());
        int order2 = childMap.get(o2.getID());

        if(order1<order2) 
            return -1;
        else if(order1>order2) 
            return 1;
        else 
            return 0;
    }
    else
        return 0;
}

添加异常

java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(TimSort.java:747)
at java.util.TimSort.mergeAt(TimSort.java:483)
at java.util.TimSort.mergeCollapse(TimSort.java:410)
at java.util.TimSort.sort(TimSort.java:214)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at java.util.Collections.sort(Collections.java:217)


推荐答案

您的 compare()方法 / em> 。如果 A == B B == C ,则 A 必须等于 C

Your compare() method is not transitive. If A == B and B == C, then A must be equal to C.

现在考虑这种情况:

A B C ,假设 containsKey()方法返回以下结果:

For A, B, and C, suppose the containsKey() method return these results:


  • childMap.containsKey(A.getID())返回 true

  • childMap.containsKey(B.getID())返回 false

  • childMap.containsKey(C.getID())返回 true

  • childMap.containsKey(A.getID()) returns true
  • childMap.containsKey(B.getID()) returns false
  • childMap.containsKey(C.getID()) returns true

此外,考虑订单 A.getId()!= B.getId()

Also, consider orders for A.getId() != B.getId().

因此,


  1. A 会返回 0 ,如 if 条件将 false => A == B

  2. code> B C 会返回 0 $ c> if 条件将为 false => B == C

  1. A and B would return 0, as outer if condition will be false => A == B
  2. B and C would return 0, as outer if condition will be false => B == C

但是, A C ,可以返回 -1 1 / code>块。所以, A!= C 。这违反了传递性原则。

But, A and C, could return -1, or 1, based on your test inside the if block. So, A != C. This violates the transitivity principle.

我想你应该在 else 块中添加一些条件, 如果阻止。

I think, you should add some condition inside your else block, that performs check similar to how you do in if block.

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

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