In the Standard Java API, are there any scenarios where ==
will return true
, but equals
will return false
.
I'm not sure if this is exactly what you have in mind, but implementations of equals
are not required to be threadsafe, and are not required to explicitly check if the argument is the same instance as this
. So it's quite possible, in principle, for foo.equals(foo)
to return false
if foo
is simultaneously being modified in another thread.
I doubt any JDK class is explicitly documented as not including this check; rather, that's considered an implementation detail, except for classes where that is the only check. But I've managed to get sb.equals(sb)
to at least raise an ArrayIndexOutOfBoundsException
when sb
is a StringBuilder
to which another thread is busily adding elements; so if you're particularly unlucky in your timing, it should also be capable of returning false
.
Additionally, would there be any possible benefit to have such a behavior?
I really don't think so. The whole purpose of equals
is to support things like Set
and Map
and Assert.assertEquals
and so on. There are plenty of use-cases that don't use equals
at all, but I can't imagine a non-terrible piece of code that does use equals
but wants it to not denote a form of equality that's satisfied by identity.
That said, it's certainly possible for a non-terrible piece of code to have a bug that accidentally causes this. For example, I mentioned in a comment above that java.util.Date
and java.sql.Timestamp
have a design mistake (now officially codified) whereby date.equals(ts)
can be true
but ts.equals(date)
is false
. Someone trying to address this sort of issue might modify java.util.Date
to include a check if (that.getClass() == Date.class)
; but then this would result in a non-reflexive equals
implementation in any subclass that didn't explicitly override the parent implementation. (Of course, I wouldn't expect such a mistake in the JDK.)
Writing equals
correctly in the face of inheritance is actually rather tricky, but fortunately there's a known solution that addresses all the intricacies in a simple way: http://www.artima.com/lejava/articles/equality.html.