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?
.equalsIgnoreCase()
is the fastest comparison if it is appropriate, otherwise.equals()
is what you want. – AzalcompareTo() == 0
does not necessarily imply equality in all cases". This is absolutely correct! This is exactly what the phrase "consistent with equals" means in the Java API specifications, for example in the Comparable class specification. For example, String's comparison method is consistent with equals, but BigDecimal's comparison method is inconsistent with equals. – Guava