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.

最初の 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 に答える