2013-08-01 57 views
0

我有这个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函数的任何行。

+1

这将是,如果你发布非常有用抛出的错误。 – jsedano

+0

如果你想实现'Comparable',注意这个签名是一个通用的,所以在运行时任何类的对象都可以传递给你的'compareTo'方法。另外,Comparable的契约特别指出'compareTo(null)'应该抛出'NullPointerException',而不是返回“这些都是相等的”(0)。 – chrylis

+0

像这样: 'if(followTarget == null || otherEntity ==null‖otherEntity.followTarget ==null‖!otherEntity.follows)throw new NullPointerException();' 'if(this.followTarget!= otherEntity .followTarget)抛出new InputMismatchException();' 我似乎无法看到代码功能正常工作 –

回答

相关问题