我有這個compareTo函數,它繼續,雖然不總是,拋出關於它的一般合約的錯誤,如果你已經通過Comparable類進行排序,可能會碰到一些點。Java Comparable Object Sorting:compareTo(Object)error
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函數的任何行。
這將是,如果你發佈非常有用拋出的錯誤。 – jsedano
如果你想實現'Comparable',注意這個簽名是一個通用的,所以在運行時任何類的對象都可以傳遞給你的'compareTo'方法。另外,Comparable的契約特別指出'compareTo(null)'應該拋出'NullPointerException',而不是返回「這些都是相等的」(0)。 – chrylis
像這樣: 'if(followTarget == null || otherEntity ==null‖otherEntity.followTarget ==null‖!otherEntity.follows)throw new NullPointerException();' 'if(this.followTarget!= otherEntity .followTarget)拋出new InputMismatchException();' 我似乎無法看到代碼功能正常工作 –