In the standard Java API, are there any scripts in which ==
will return true
, but equals
will return false
.
I'm not sure if this is exactly what you mean, but equals
implementations should not be thread safe and should not explicitly check if the argument is the same instance as this
. Therefore, in principle, it is possible for foo.equals(foo)
to return false
if foo
simultaneously changing in another thread.
I doubt that any JDK class is explicitly documented as not including this check; rather, considering the implementation detail, except for classes where this is the only check. But I managed to get sb.equals(sb)
to at least raise an ArrayIndexOutOfBoundsException
when sb
is a StringBuilder
to which another thread repeatedly adds elements; therefore, if you are particularly unlucky in your time, it should also return false
.
Also, would there be any possible benefit to such behavior?
I really donโt think so. The goal of equals
is to support things like Set
and Map
and Assert.assertEquals
etc. There are many precedents that donโt use equals
at all, but I canโt imagine a scary piece of code that uses equals
, but wants it not to represent a form of equality that satisfies an identity.
However, of course, for the non-scary part of the code, there is an error that accidentally causes this. For example, I mentioned in a comment above that java.util.Date
and java.sql.Timestamp
have a design error (now officially codified) in which date.equals(ts)
can be true
, but ts.equals(date)
is false
. Someone trying to solve this problem might modify java.util.Date
to enable if (that.getClass() == Date.class)
; but then this will lead to a non-reflexive implementation of equals
in any subclass that does not explicitly override the parent implementation. (Of course, I would not expect such an error in the JDK.)
Writing equals
correctly in the face of inheritance is actually quite complicated, but, fortunately, there is a well-known solution that tracks all the difficulties: http://www.artima.com/lejava/articles/equality.html .