比较方法抛出异常:比较方法违反了其总体合同 [英] Compare method throw exception: Comparison method violates its general contract

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

问题描述


可能重复:

为什么我的比较方法抛出异常—比较方法违反了其一般合同!

我有这个代码: p>

I've this code:

class TimeComparatorTipo0 implements Comparator {
@Override
public int compare(Object a, Object b) {
     String Time1   = ((DataImportedTipo0) a).ora;
     Long   VolTot1 = Long.parseLong(((DataImportedTipo0) a).volume_totale);

     String Time2   = ((DataImportedTipo0) b).ora;
     Long   VolTot2 = Long.parseLong(((DataImportedTipo0) b).volume_totale);

    if (Time1.equals(Time2))
    {          
       if ( VolTot1.compareTo(VolTot2) > 0)
         return 1;
       else
         return -1;         
    }
    else
      return Time1.compareTo(Time2);
     }
};

有时它抛出了这个例外:

Sometimes it thrown this exception:

java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:868)
at java.util.TimSort.mergeAt(TimSort.java:485)
at java.util.TimSort.mergeForceCollapse(TimSort.java:426)
at java.util.TimSort.sort(TimSort.java:223)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at java.util.Collections.sort(Collections.java:217)
at ManageUrl.DownloadUrl.StartThreadDowloadTipo0(DownloadUrl.java:893)
at ManageUrl.DownloadUpdateWorkflow$ConsumerTipo0.run(DownloadUpdateWorkflow.java:278)

为什么?

1)我该如何避免?
2)我如何抓住这个异常?

1) how can I avoid it? 2) how can i catch this exception ?

提前感谢

推荐答案

如果您有两个元素相等时,您将获得 a b $ c> compare(a,b)== -1 和 compare(b,a)== -1

If you have two elements when are equal a and b you will get compare(a, b) == -1 and compare(b, a) == -1 which doesn't make any sense.

您可以使用

class TimeComparatorTipo0 implements Comparator<DataImportedTipo0> {
@Override
public int compare(DataImportedTipo0 a, DataImportedTipo0 b) {
    String Time1 = a.ora, Time2 = b.ora;

    int cmp = Time1.compareTo(Time2);
    if (cmp == 0) {
       // avoid expensive operations.
       Long VolTot1 = Long.parseLong(a.volume_totale);
       Long VolTot2 = Long.parseLong(b.volume_totale);
       cmp = VolTot1.compareTo(VolTot2);
    }
    return cmp;

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

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