Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any scenarios where `==` is true but `equals` is false?

Tags:

java

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?

like image 867
Eli Sadoff Avatar asked Jan 19 '17 18:01

Eli Sadoff


2 Answers

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.

like image 113
Afforess Avatar answered Oct 08 '22 09:10

Afforess


In the Standard Java API, are there any scenarios where == will return true, but equals will return false[?]

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

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.

like image 34
John Bollinger Avatar answered Oct 08 '22 09:10

John Bollinger