简体   繁体   English

在Java7中重写compareTo和Compare

[英]Overriding compareTo and Compare in java7

Do I need to override the equals() method when ever I override the CompareTo and Compare method in java, in order to satisfy the Comparable contract ? 为了满足Comparable合同,我在Java中重写CompareTo和Compare方法时是否需要重写equals()方法? Will this create any issues when I do a Collections.sort or Array.sort? 当我执行Collections.sort或Array.sort时,这会产生任何问题吗?

From the Javadoc for Comparator 从Javadoc for Comparator

It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). 通常是这种情况,但并非严格要求(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." 推荐的语言是“注意:此比较器施加与等式不一致的顺序”。

This means that you don't generally need to override equals() . 这意味着您通常不需要重写equals() You probably shouldn't do this, unless you want your Comparator to return a non-zero comparison for two values which return true when compared with equals . 除非您希望Comparator对两个值返回非零比较,而两个值与equals比较时返回true ,则您可能不应该这样做。

If you think that the existence of a comparison requires you to change the definition of what it means for two things to be equal, then you've probably designed something badly. 如果您认为比较的存在要求您更改两个事物相等意味着什么的定义,那么您可能设计得很糟糕。

From Comparable : Comparable

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C . 当且仅当e1.compareTo(e2) == 0 C类的每个e1e2具有与e1.equals(e2)相同的布尔值时,才可以认为C类的自然排序与equals一致。 Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false . 请注意, null不是任何类的实例,即使e.equals(null)返回falsee.compareTo(null)仍应引发NullPointerException

It is strongly recommended (though not required) that natural orderings be consistent with equals . 强烈建议(尽管不是必需的)自然顺序应与equals保持一致 This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. 之所以如此,是因为没有显式比较器的排序集(和排序映射)与自然排序与等式不一致的元素(或键)一起使用时,其行为“奇怪”。 In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method. 特别是,这样的排序集(或排序图)违反了根据equals方法定义的集合(或图)的一般约定。

(emphasis mine) (强调我的)

So you don't need to override equals() (ie it will not cause a problem within the standard sort methods since they use only compareTo() , nor does it violate the contract of Comparable ), but it certainly wouldn't hurt. 因此,您不需要重写equals() (即,由于它们仅使用compareTo() ,因此不会在标准sort方法内引起问题,也不会违反Comparable的约定),但肯定不会受到伤害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM