有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java例外。lang.IllegalArgumentException:比较法违反其一般合同含义?

现在我知道之前已经有人问过关于这个主题的问题,但是我的问题并不是关于一个特定的例子

我只是想了解所述错误的含义。我在互联网上所能找到的只是基于示例的解决方案。有人能解释一下这个错误的核心是什么,什么时候会发生

我只是一个试图学习的学生,无法通过其他渠道理解这一点,所以请耐心等待我

谢谢


共 (2) 个答案

  1. # 1 楼答案

    如果您不想要一个具体的例子,只需转到合同的规范,例如可以在比较器javadoc中找到:

    A comparison function, which imposes a total ordering on some collection of objects ... The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S. ...

    等等。更重要的是compare()方法的javadoc:

    Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

    In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

    The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

    The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

    Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.

    It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."

    这些规范定义了“合同”的内容。当你违反了合同,并且系统能够检测到,你最终会出现上述异常

  2. # 2 楼答案

    Comparable定义了compareTo方法的约定:

    • The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

    • The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

    • Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

    如果实现者没有确保这些条件,则违反了合同,Comparable.compareTo方法的用户可以报告,但有例外