compareTo() vs. equals() compareTo() vs. equals() java java

compareTo() vs. equals()


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.


The 2 main differences are that:

  1. equals will take any Object as a parameter, but compareTo will only take Strings.
  2. equals only tells you whether they're equal or not, but compareTo 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.


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.