java compareTo比较方法违反了其一般合同

时间:2014-06-16 14:05:44

标签: java sorting compareto

我正在尝试对集合进行排序并获得以下异常:

java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.util.ComparableTimSort.mergeHi(ComparableTimSort.java:835)
    at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:453)
    at java.util.ComparableTimSort.mergeCollapse(ComparableTimSort.java:376)
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:182)
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
    at java.util.Arrays.sort(Arrays.java:472)
    at java.util.Collections.sort(Collections.java:155)

我知道compareTo的3份合约:

  • x.compareTo(y)> 0&& y.compareTo(z)> 0)暗示x.compareTo(z)> 0
  • sgn(x.compareTo(y))== -sgn(y.compareTo(x))
  • x.compareTo(y)== 0表示sgn(x.compareTo(z))== sgn(y.compareTo(z))

代码如下。我可以看到Long.intValue()有可能被截断,但据我所知,这不应该违反合同。

public class Bar implements Comparable<Bar>{

private static final int LOWER = 1;
private static final int HIGHER = -1;
private boolean isNoPriority;
private int priority;
private String tradeId;
private long tradeVersion;



public Bar(boolean isNoPriority, int priority, String tradeId,long tradeVersion) {
    super();
    this.isNoPriority = isNoPriority;
    this.priority = priority;
    this.tradeId = tradeId;
    this.tradeVersion = tradeVersion;
}   
@Override
public int compareTo(Bar o) {

    if (isNoPriority && !o.isNoPriority){               
        return LOWER;
    }
    if (!isNoPriority && o.isNoPriority){
        return HIGHER;
    }

    if (priority == o.priority) {
        if (tradeId.compareToIgnoreCase(o.tradeId) == 0){                   
            return Long.valueOf(tradeVersion).intValue() - Long.valueOf(o.tradeVersion).intValue();
        }
        else {
            return tradeId.compareToIgnoreCase(o.tradeId);                              
        }
    }
    else if (priority < o.priority) {               
        return LOWER;
    }
    else if (priority > o.priority){                
        return HIGHER;          
    } else {
        return 0;
    }

}
}

我无法理解这个compareTo实现的错误。

1 个答案:

答案 0 :(得分:2)

您已回答了自己的问题。如果其中一个长值被“截断”,则可能会从非常大的正数变为负数。当返回负值时,这可能导致返回正值。它也可能导致返回0表示不相等的2个值。

使用Long compareTo。

,而不是减去int值

http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#compare(long,%20long)