Why is there "==" inside String.equals?

Why is Java comparing (this == another String) inside equalsIgnoreCase method to test for string insensitivity?

Also, does String equals compare (this == another String) to compare two objects?

Java 6: String implementation of equalsIgnoreCase class given below.

 public boolean equalsIgnoreCase(String anotherString) {
        return (this == anotherString) ? true :
               (anotherString != null) && (anotherString.count == count) &&
           regionMatches(true, 0, anotherString, 0, count);
    }

      

Java 6: The String class is equal to the implementation below.

 public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }

      

+3


source to share


3 answers


Why is Java comparing (this == another String) inside equalsIgnoreCase method to test for string insensitivity?

This is optimization. If the reference passed is exactly the same as this

then it equals

should return true

, but we don't need to search for any fields, etc. Everything is the same as herself. From the documentation for Object.equals(Object)

:

The equals method implements an equivalence relation for non-null object references:

  • This is reflective: for any non-zero reference x, x.equals (x) must return true.
  • ...


It is very common for equality tests to start with:

  • Is the other link equal this

    ? If so, return true.
  • Is the other link null? If so, return false.
  • Is another object reference of the wrong type? If so, return false.

Then you move on to the types of checks.

+10


source


==

true when compared to the same object - with an efficiency gain more likely than any other class due to String interning .

Please note that this code:

return (this == anotherString) ? true : <rest of line>

      



could have been written (more elegantly IMHO) as:

return this == anotherString || <rest of line>

      

+2


source


 this == another object 

      

This is a basic method check equals

for almost all objects, not just the String class. It is effective as well as good practice to test it in your own class.
The logic is simple , if both have the same reference, then they always refer to the same object , so they are equal .

You don't need any other comparison to say they are equal if this == another object

true.

+1


source







All Articles