问题描述
以下是我的比较器的比较方法。我不知道是什么问题。我查找了其他类似的标题问题和答案堆栈溢出,但不知道什么是我的方法,但我不断得到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())
returnstrue
childMap.containsKey(B.getID())
returnsfalse
childMap.containsKey(C.getID())
returnstrue
此外,考虑订单 A.getId()
!= B.getId()
Also, consider orders for A.getId()
!= B.getId()
.
因此,
-
A
和会返回
0
,如if
条件将false
=>A == B
- code> B 和
C
会返回0
$ c> if 条件将为false
=>B == C
A
andB
would return0
, as outerif
condition will befalse
=>A == B
B
andC
would return0
, as outerif
condition will befalse
=>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:比较方法违反其一般合同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!