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

2019-05-09 23:57发布

问题:

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).