当我重写 java 中的 CompareTo 和 Compare 方法时,是否需要重写 equals() 方法,以满足 Comparable 契约?当我执行 Collections.sort 或 Array.sort 时,这会产生任何问题吗?
最佳答案
来自 Comparator
的 Javadoc
It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."
这意味着您通常不需要重写equals()
。您可能不应该这样做,除非您希望 Comparator
返回两个值的非零比较,并且与 equals
比较时返回 true
>.
如果您认为比较的存在需要您更改两个事物相等的定义,那么您可能设计得很糟糕。
关于java - 在java7中重写compareTo和Compare,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034907/