比较方法抛出异常:比较方法违反了其一般合同

时间:2012-04-19 18:01:57

标签: java exception comparator contract

  

可能重复:
  why does my compare method throw exception — Comparison method violates its general contract!

我有这段代码:

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

有时会抛出此异常:

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 个答案:

答案 0 :(得分:5)

如果你有两个元素,当它们相等ab时你会得到compare(a, b) == -1compare(b, a) == -1这没有任何意义。

您可以使用

简化代码并提高效率
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;