我有这个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函数的任何信息。
答案 0 :(得分:0)
我前段时间遇到Comparable
违反合同的行为,这与返回相互矛盾的结果有关;在某些情况下,您的方法可能会为object1.compareTo(object2)
和object2.compareTo(object1)
返回1(或-1)
你可以在这里找到类似的问题.-
why does my compare method throw exception -- Comparison method violates its general contract!