【问题标题】:Why does this code throw exception - Comparison method violates its general contract为什么这段代码会抛出异常 - 比较方法违反了它的一般合同
【发布时间】:2017-01-13 12:26:01
【问题描述】:

我正在使用以下引发 IllegalArgumentException 的代码:

// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.

package jodd.util;

import java.util.Comparator;

/**
 * Compares two strings in natural, alphabetical, way.
 */
public class NaturalOrderComparator<T> implements Comparator<T> {

    protected final boolean ignoreCase;

    public NaturalOrderComparator() {
        ignoreCase = false;
    }

    public NaturalOrderComparator(boolean ignoreCase) {
        this.ignoreCase = ignoreCase;
    }

    /**
     * Compare digits at certain position in two strings.
     * The longest run of digits wins. That aside, the greatest
     * value wins.
     */
    protected int compareDigits(String str1, int ndx1, String str2, int ndx2) {
        int bias = 0;

        while (true) {
            char char1 = charAt(str1, ndx1);
            char char2 = charAt(str2, ndx2);

            boolean isDigitChar1 = CharUtil.isDigit(char1);
            boolean isDigitChar2 = CharUtil.isDigit(char2);

            if (!isDigitChar1 && !isDigitChar2) {
                return bias;
            }
            if (!isDigitChar1) {
                return -1;
            }
            if (!isDigitChar2) {
                return 1;
            }

            if (char1 < char2) {
                if (bias == 0) {
                    bias = -1;
                }
            } else if (char1 > char2) {
                if (bias == 0) {
                    bias = 1;
                }
            } else if (char1 == 0 && char2 == 0) {
                return bias;
            }

            ndx1++;
            ndx2++;
        }
    }

    public int compare(T o1, T o2) {
        String str1 = o1.toString();
        String str2 = o2.toString();

        int ndx1 = 0, ndx2 = 0;
        int zeroCount1, zeroCount2;
        char char1, char2;

        int result;

        while (true) {
            // only count the number of zeroes leading the last number compared
            zeroCount1 = zeroCount2 = 0;

            char1 = charAt(str1, ndx1);
            char2 = charAt(str2, ndx2);

            // skip over leading spaces or zeros in both strings

            while (Character.isSpaceChar(char1) || char1 == '0') {
                if (char1 == '0') {
                    zeroCount1++;
                } else {
                    zeroCount1 = 0; // counts only last 0 prefixes, space char interrupts the array of 0s
                }
                ndx1++;
                char1 = charAt(str1, ndx1);
            }

            while (Character.isSpaceChar(char2) || char2 == '0') {
                if (char2 == '0') {
                    zeroCount2++;
                } else {
                    zeroCount2 = 0;
                }
                ndx2++;
                char2 = charAt(str2, ndx2);
            }

            // process digits

            boolean isDigitChar1 = CharUtil.isDigit(char1);
            boolean isDigitChar2 = CharUtil.isDigit(char2);

            if (isDigitChar1 && isDigitChar2) {
                result = compareDigits(str1, ndx1, str2, ndx2);
                if (result != 0) {
                    // not equals, return
                    return result;
                }
                // equal numbers
                if (zeroCount1 != zeroCount2) {
                    return zeroCount1 - zeroCount2;
                }
            }

            if (char1 == 0 && char2 == 0) {
                // the end; the strings are the same, maybe compare ascii?
                return zeroCount1 - zeroCount2;
            }

            // check when one of the numbers is just zeros
            if (isDigitChar1 || isDigitChar2) {
                if (zeroCount1 != zeroCount2) {
                    return zeroCount2 - zeroCount1;
                }
            }

            // checks when both numbers are zero
            if (zeroCount1 != zeroCount2) {
                return zeroCount1 - zeroCount2;
            }

            // compare chars
            if (ignoreCase) {
                char1 = Character.toLowerCase(char1);
                char2 = Character.toLowerCase(char2);
            }
            if (char1 < char2) {
                return -1;
            }
            if (char1 > char2) {
                return 1;
            }

            ndx1++;
            ndx2++;
        }
    }

    /**
     * Safe charAt.
     */
    private static char charAt(String s, int i) {
        if (i >= s.length()) {
            return 0;
        }
        return s.charAt(i);
    }
}

抛出异常:

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.mergeCollapse(TimSort.java:410)
    at java.util.TimSort.sort(TimSort.java:214)
    at java.util.TimSort.sort(TimSort.java:173)
    at java.util.Arrays.sort(Arrays.java:659)
    at java.util.Collections.sort(Collections.java:217)

这由以下函数调用:

@Override
    public int compare(final T o1, final T o2) {
        int result;
        final MyObject obj1 = (MyObject) o1;
        final MyObject obj2 = (MyObject) o2;

                   return     result = compareStringId(obj1.getStringId(),obj2.getStringId());           

    }

private int compareStringId(final String Id1, final String Id2) {
        return super.compare((T) Id1, (T) Id2);
    }

它在我们的本地机器上运行良好,但是在生产中失败了,我们无法连接到该机器来找出原因。可以帮忙吗

【问题讨论】:

  • super.compare((T)...) 所指的超类是什么?你为什么要把字符串转换成T?顺便说一句,您在本地和服务器上使用哪个 Java 版本?如果您的代码在本地工作,您可能正在运行一个不同的版本,它以某种方式错过了ClassCastException,这可能是在将String 转换为T 时抛出的。
  • 另一个问题:您发布了一些比较器代码,但没有显示您是如何调用它的(即代码调用Collections.sort(...))。
  • 如果 a.compareTo(b) 返回 -1,那么 b.compareTo(a) 必须返回 1。如果 a.compareTo(b) 返回 0,那么 b.compareTo(a) 也必须返回 0。您的 compareTo 方法不保留此协定。您在本地系统上没有出现异常的原因可能是因为您使用的 java 版本
  • 如果你能弄清楚在 Java8 上这个比较器失败的输入数据是什么......并在 GitHub 上向 Jodd 报告问题,那就太酷了。我试图复制,到目前为止没有运气

标签: java jodd


【解决方案1】:

问题在于 Comparator 的错误实现。根据 Java 文档,Comparator 必须同时具有自反性和传递性。在这种情况下,不能保证传递性。之前的 Java 8 不是一个大问题,即排序实现 (MergeSort) 不会抛出异常。 Java8 将默认排序实现更改为TimSort,这对具有无效合同的比较器更加敏感,因此它可能会抛出异常。

但是,这对您解决问题没有多大帮助。怎么样查看最新版本的同班here。它已升级为支持比较器合约,而且它在某些边缘情况下工作得更好,更不用说对口音的初始支持了。

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多