0

我有这个 compareTo 函数,尽管并非总是如此,但它会继续抛出关于其一般合同的错误,如果你已经通过 Comparable 类进行了排序,则可能在某个时候遇到了错误。

public int compareTo(FollowableEntity otherEntity) {
    if(followTarget == null || otherEntity == null || otherEntity.followTarget == null || !otherEntity.follows) return 0;
    if(this.followTarget != otherEntity.followTarget) return 0;
    if(this.getDistanceSqToEntity(followTarget) == otherEntity.getDistanceToEntity(followTarget) && this.getDistanceSqToEntity(otherEntity) < this.getDistanceSqToEntity(followTarget)) return 1;
    if(this.getDistanceSqToEntity(followTarget) == otherEntity.getDistanceToEntity(followTarget) && this.getDistanceSqToEntity(otherEntity) > this.getDistanceSqToEntity(followTarget)) return -1;
    if(this.getDistanceSqToEntity(followTarget) < otherEntity.getDistanceSqToEntity(followTarget) && (this.getDistanceSqToEntity(followTarget) < this.getDistanceSqToEntity(otherEntity))) return -1;
    if(this.getDistanceSqToEntity(followTarget) < otherEntity.getDistanceSqToEntity(followTarget) && (this.getDistanceSqToEntity(followTarget) > this.getDistanceSqToEntity(otherEntity))) return 1;
    if(this.getDistanceSqToEntity(followTarget) > otherEntity.getDistanceSqToEntity(followTarget)) return 1;

    return 0;

}


FollowableEntity has double position values: posX, posY, posZ.
(FollowableEntity(obj)).getDistanceSqToEntity(FollowableEntity) returns the squared distance between the entities as a double. (x1 - x)^2 + (y1 - y)^2 + (z1 - z)^2.

前两个条件在逻辑上不应该在比较时发生,但我还是把它们放在那里。

我不确定是什么条件导致错误被抛出,因为它是唯一的一次,碰巧有几十个实体围绕彼此旋转以达到他们的目标。

这是日志的一部分,我的日志记录实用程序效率很低。

17:23:37 - Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!
17:23:37 -  at java.util.ComparableTimSort.mergeLo(ComparableTimSort.java:714)
17:23:37 -  at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:451)
17:23:37 -  at java.util.ComparableTimSort.mergeCollapse(ComparableTimSort.java:376)
17:23:37 -  at java.util.ComparableTimSort.sort(ComparableTimSort.java:182)
17:23:37 -  at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
17:23:37 -  at java.util.Arrays.sort(Arrays.java:472)
17:23:37 -  at java.util.Collections.sort(Collections.java:155)

之后它指向调用 Collections.sort() 的行,但没有告诉我有关 compareTo 函数的任何信息。

4

1 回答 1

0

Comparable前段时间遇到合同违约,与退货结果矛盾有关;有可能在某些情况下,您的方法同时返回 1(或 -1)object1.compareTo(object2)并且object2.compareTo(object1)

你可以在这里找到类似的问题。-

为什么我的比较方法会抛出异常——比较方法违反了它的一般合同!

于 2013-08-01T21:34:36.127 回答