比较方法违反其一般合同异常 [英] Comparison method violates its general contract Exception

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

问题描述

下面是一个代码块,导致指定的异常,

Below is a block of code that results in exception as indicated,

代码:

Collections.sort( arrayList, new Comparator() 
{
    public int compare( Object o1, Object o2 )
    {
        TypeAdapterSort tas1 = ( TypeAdapterSort ) o1;
        TypeAdapterSort tas2 = ( TypeAdapterSort ) o2;
        if ( tas1.order < tas2.order )
            return -1;
        else
            return 1;
    }
} );

例外:

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.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)

当我运行相同的代码作为一个独立的程序,这个问题永远不会发生。比较器的问题是什么?有没有办法在独立代码中重现这个问题?

When I run the same code as a standalone program, the issue never occurs. What is the issue with the comparator here? Is there a way to reproduce the issue in a standalone code?

这个问题只发生在Java 1.7上,因为在Arrays.sort& Collections.sort。如何更改上述代码以避免此问题?

This issue occurs only on Java 1.7 as there has been change in the implementation on Arrays.sort & Collections.sort. How to change the above code to avoid the issue?. Also, how to reproduce this issue in a standalone code?

推荐答案

您需要在相等的对象上返回0。

You need to return 0 on equal objects.

        if ( tas1.order < tas2.order ){
            return -1;
        } else if ( tas1.order == tas2.order ){
            return 0;
        } else {
            return 1;
        }

您可以阅读这里更多

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

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