compareTo() vs. equals()
When testing for equality of String
's in Java I have always used equals()
because to me this seems to be the most natural method for it. After all, its name already says what it is intended to do. However, a colleague of mine recently told me had been taught to use compareTo() == 0
instead of equals()
. This feels unnatural (as compareTo()
is meant to provide an ordering and not compare for equality) and even somewhat dangerous (because compareTo() == 0
does not necessarily imply equality in all cases, even though I know it does for String
's) to me.
He did not know why he was taught to use compareTo()
instead of equals()
for String
's, and I could also not find any reason why. Is this really a matter of personal taste, or is there any real reason for either method?
Solution 1:
A difference is that "foo".equals((String)null)
returns false while "foo".compareTo((String)null) == 0
throws a NullPointerException. So they are not always interchangeable even for Strings.
Solution 2:
The 2 main differences are that:
-
equals
will take any Object as a parameter, butcompareTo
will only take Strings. -
equals
only tells you whether they're equal or not, butcompareTo
gives information on how the Strings compare lexicographically.
I took a look at the String class code, and the algorithm within compareTo and equals looks basically the same. I believe his opinion was just a matter of taste, and I agree with you -- if all you need to know is the equality of the Strings and not which one comes first lexicographically, then I would use equals
.
Solution 3:
When comparing for equality you should use equals()
, because it expresses your intent in a clear way.
compareTo()
has the additional drawback that it only works on objects that implement the Comparable
interface.
This applies in general, not only for Strings.