Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compareTo() vs. equals()

People also ask

What is difference between equals () and compareTo () method?

equals() checks if two objects are the same or not and returns a boolean. compareTo() (from interface Comparable) returns an integer. It checks which of the two objects is "less than", "equal to" or "greater than" the other.

Why compareTo () should be consistent to equals () method in Java?

2) CompareTo must be in consistent with equals method e.g. if two objects are equal via equals() , there compareTo() must return zero otherwise if those objects are stored in SortedSet or SortedMap they will not behave properly.

What does compareTo () do?

Definition and Usage. The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.

What is the relationship between compareTo and equals C#?

CompareTo() tells you which, and if, one is greater/less than the other, while Equals() simply tells you if they are equivalent values.


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.


compareTo has do do more work if the strings have different lengths. equals can just return false, while compareTo must always examine enough characters to find the sorting order.


In String Context:
compareTo: Compares two strings lexicographically.
equals: Compares this string to the specified object.

compareTo compares two strings by their characters (at same index) and returns an integer (positive or negative) accordingly.

String s1 = "ab";
String s2 = "ab";
String s3 = "qb";
s1.compareTo(s2); // is 0
s1.compareTo(s3); // is -16
s3.compareTo(s1); // is 16