java.lang.Comparable和equals [英] java.lang.Comparable and equals
问题描述
如果我为一个类实现 java.lang.Comparable
,我还是要覆盖 equals()
方法?或者可比较
是否也适用于等于
?
If I implement java.lang.Comparable
for a class, do I still have to override the equals()
method? Or will the Comparable
work for equals
as well?
如果答案是否,那么如果出现一些差异怎么办?假设我在 equals()
方法中将两个对象称为相等的方式不同于我在<$ c $中将同一类的两个对象称为相等的方式c> compareTo() 可比较
。
If the answer is no, then what if some discrepancy arises? Let's say the way I term two objects as equal within the equals()
method is different from the way I term two objects of the same class as equal within the compareTo()
of the Comparable
.
此外,如果我实施可比较
,我是否还必须覆盖 equals()
?
Moreover, if I implement Comparable
, do I also have to override equals()
?
推荐答案
虽然建议(并且非常明智)有 a.compareTo(b)== 0
暗示 a.equals(b)
(反之亦然),不是必需的。 可比较
用于对一系列对象执行排序时使用,而等于()
只测试直接平等。
While it is recommended (and pretty sensible) that having a.compareTo(b) == 0
imply that a.equals(b)
(and visa versa), it is not required. Comparable
is intended to be used when performing an ordering on a series of objects, whereas equals()
just tests for straight equality.
此链接有一些关于正确实施 compareTo
的信息。
This link has some good information on implementing compareTo
properly.
这篇关于java.lang.Comparable和equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!