equals()vs compareTo()in Comparator / able(Theoretical) [英] equals() vs compareTo() in Comparator/able (Theoretical)
问题描述
我不懂得Javadoc:
类C的自然排序被认为与equals相一致if和只有当
(e1.compareTo((Object)e2)== 0)具有与e1.equals((Object)e2)相同的布尔值,对于
每个类C的e1和e2。
为什么会这样?
e1.equals(e2)= true应该总是暗示e1.compareTo(e2)== 0,但我不明白为什么相反应该是真的。比较不平等! 2个相等的对象应该与零相比较,但是如果排序的标准与它们的情况不相关,则2个不同的对象应该能够比较为0。我的意思是,有不同的对象等于不正确,但不同的对象与0比较为什么不?
编辑:后来说,对于一些兼容性问题,因此问题
Javadoc不是说它是有一个与equals不一致的比较。
当你得到选择时,通常最好使比较与equals相一致,使得给定的A和B,A小于,等于或大于B,但不是以这种方式工作。这是重要的,你记录下来,但调用者可能会非常困惑的排序,这是意想不到的等于。
I don,t understand Javadoc:
The natural ordering for a class C is said to be consistent with equals if and only if
(e1.compareTo((Object)e2) == 0) has the same boolean value as e1.equals((Object)e2) for
every e1 and e2 of class C.
Why should be that way?
I understand that e1.equals(e2)=true should always imply e1.compareTo(e2)==0, but I cannot understand why the opposite should be true. Compareness is not equalness! 2 equal objects should be compared to zero, but 2 differents ones should be able to compareTo 0 if the criteria for sorting is not relevant in their case. I mean, having different objects equaling is not correct, but different objects with a 0 comparation why not?
EDIT: Later it says that consistency is strong recommended, for some compatibility issues, and hence the question
That Javadoc isn't saying it's wrong to have a comparison which isn't consistent with equals. It's just defining the terminology for a comparison being consistent with equals.
When you get the choice it's generally nice to make a comparison consistent with equals, such that given A and B, A is either less than, equal to or greater than B - but it doesn't have to work that way.
It is important that you document this though - callers could get very confused with an ordering which is unexpectedly not consistent with equals.
这篇关于equals()vs compareTo()in Comparator / able(Theoretical)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!