Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: equals and ==

Lets see we have 2 references to instances of a user-defined class, a and b in Java. Can there ever be a situation where a == b but a.equals(b) return false?

like image 311
Vince Avatar asked Sep 08 '26 15:09

Vince


2 Answers

Sure! The implementation of .equals() is completely up to the class, so I could write:

class Foo
    public boolean equals(Object other) {
        return false;
    }
}

Now it doesn't matter what two instances you pass — even the exact same instance twice — I'm always going to say they're not equal.

This particularly setup is silly, but it illustrates that you can get a false result from .equals() for the same object twice.

Note that we're talking here about what can happen, not what should. No class should ever implement a .equals method that claims an object isn't equal to itself. For trusted code, it's reasonable to assume this will never happen.

like image 200
VoteyDisciple Avatar answered Sep 11 '26 03:09

VoteyDisciple


if a == b then a.equals(b) should be true. And if a.equals(b) then maybe a == b but not necessarily.

The == operator just test if both are referencing the same object. While equals executes a logic that you implemented. The last one can be overridden the first one is an operator from the language, and such as cannot be overridden in Java.

References

what is the difference between == operator and equals()? (with hashcode() ???)

From java.lang.Object documentation:

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

  1. It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  2. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  3. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  4. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  5. For any non-null reference value x, x.equals(null) should return false.
like image 21
Francisco Spaeth Avatar answered Sep 11 '26 05:09

Francisco Spaeth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!