In the Standard Java API, are there any scenarios where == will return true, but equals will return false. While theoretically this could be written into a user-defined class rather trivially like this
class A {
public boolean equals(Object o) {
return this != o;
}
}
Are there any actually baked in examples where for some objects b and c, b == c will return true, but b.equals(c) returns false? Additionally, would there be any possible benefit to have such a behavior?
No*.
The contract for equals has 5 rules, and the first one covers this case:
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.
Any object in the Java standard library that violates reflexivity would be a bug, and if you do discover such an object in the API, report it to Oracle.
*Less can be said for third-party libraries. Developers make mistakes or are ignorant of the equals contract. Generally this also qualifies as a bug in a third-party library, but YMMV.
In the Standard Java API, are there any scenarios where
==will returntrue, butequalswill returnfalse[?]
Not as far as I am aware, and I am confident that any examples you discovered would be considered bugs.
In particular, if x and y are references such that x == y, then it must be the case that x.equals(y) evaluates to the same result as x.equals(x). The contract for Object.equals() (in its docs) says this, in part:
The
equalsmethod implements an equivalence relation on non-null object references:
- It is reflexive: for any non-null reference value
x,x.equals(x)should returntrue.
Thus any override of Object.equals() is semantically incorrect if it produces, for any references x and y, the result that x == y && !x.equals(y) is true.
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