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?
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.
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.
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:
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- 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.
- 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.
- 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.
- For any non-null reference value x, x.equals(null) should return false.
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