equals() vs compareTo() in Comparator/able (Theoretical)

我的未来我决定 提交于 2020-02-28 07:35:06

问题


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


回答1:


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.




回答2:


They are just talking about natural ordering. You may be after a different kind of order




回答3:


The java doc talks about natural ordering. You are free to compare them otherwise. But if it is about natural ordering then don't you think, it has to be both ways?

Not even after 50 moons a day will arrive where we can see the natural ordering of intergers are reversed ;)




回答4:


As an example consider BigDecimal class, in this class the methods equals and compareTo are not consistent between each other:

The equals documentation says:

public boolean equals(Object x)

Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).



来源:https://stackoverflow.com/questions/10833635/equals-vs-compareto-in-comparator-able-theoretical

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!