Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equals(...) and equalsIgnoreCase(...)

Tags:

java

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?

like image 898
Vaibhav Bajpai Avatar asked Mar 20 '10 12:03

Vaibhav Bajpai


People also ask

Which is faster equals or equalsIgnoreCase?

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.

What does equalsIgnoreCase mean?

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.

Is == and .equals the same?

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.

What is the difference between '= =' and equalsIgnoreCase )'?

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.


1 Answers

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).

like image 93
Péter Török Avatar answered Oct 27 '22 15:10

Péter Török