java 比较方法抛出异常:比较方法违反了它的一般约定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10234038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:08:55  来源:igfitidea点击:

Compare method throw exception: Comparison method violates its general contract

javaexceptioncomparatorcontract

提问by famedoro

Possible Duplicate:
why does my compare method throw exception — Comparison method violates its general contract!

可能的重复:
为什么我的比较方法会抛出异常——比较方法违反了它的一般契约!

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)

Why ?

为什么 ?

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

1)我怎样才能避免它?2)我怎样才能捕捉到这个异常?

Thanks in advance.

提前致谢。

回答by Peter Lawrey

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

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

You can simplify the code with and make it more efficient with

您可以简化代码并提高效率

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;