Why do we have equals()
and equalsIgnoreCase()
as two different methods, when equals()
could have been overloaded with a special ignoreCase
argument to provide equalsIgnoreCase()
functionality?
equalsIgnoreCase() is 20–50% faster than the equals(param. toLowerCase()) pattern. And 25 times faster when the parameter doesn't match the constant string. Let's take a look at the String.
Definition and Usage The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.
The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.
The only difference between them is that the equals() methods considers the case while equalsIgnoreCase() methods ignores the case during comparison. For e.g. The equals() method would return false if we compare the strings “TEXT” and “text” however equalsIgnoreCase() would return true.
The method equals()
is inherited from Object
, so its signature should not be changed. equals()
can often be used without actually knowing the concrete class of the object, e.g. when iterating through a collection of objects (especially before Java 5 generics). So then you wouldn't even see the other equals()
without downcasting your object to String
first.
This was a design choice from the creators of Java to make the idiom of using equals()
usable exactly the same way for all objects.
Moreover, IMO
if (string1.equalsIgnoreCase(string2)) ...
is more readable, thus less error-prone than
if (string1.equals(string2, true)) ...
Of course, in your own classes you are free to add an equals()
with different signature (on top of the standard equals()
, that is).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With