“Comparison method violates its general contract!”

前端 未结 11 2069
梦如初夏
梦如初夏 2020-11-21 06:07

Can someone explain me in simple terms, why does this code throw an exception, \"Comparison method violates its general contract!\", and how do I fix it?

pri         


        
11条回答
  •  一向
    一向 (楼主)
    2020-11-21 06:43

    Your comparator is not transitive.

    Let A be the parent of B, and B be the parent of C. Since A > B and B > C, then it must be the case that A > C. However, if your comparator is invoked on A and C, it would return zero, meaning A == C. This violates the contract and hence throws the exception.

    It's rather nice of the library to detect this and let you know, rather than behave erratically.

    One way to satisfy the transitivity requirement in compareParents() is to traverse the getParent() chain instead of only looking at the immediate ancestor.

提交回复
热议问题