Issue
I'm using Eclipse to generate .equals()
and .hashCode()
, and there is an option labeled "Use 'instanceof' to compare types". The default is for this option to be unchecked and use .getClass()
to compare types. Is there any reason I should prefer .getClass()
over instanceof
?
Without using instanceof
:
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Using instanceof
:
if (obj == null)
return false;
if (!(obj instanceof MyClass))
return false;
I usually check the instanceof
option, and then go in and remove the "if (obj == null)
" check. (It is redundant since null objects will always fail instanceof
.) Is there any reason that's a bad idea?
Solution
If you use instanceof
, making your equals
implementation final
will preserve the symmetry contract of the method: x.equals(y) == y.equals(x)
. If final
seems restrictive, carefully examine your notion of object equivalence to make sure that your overriding implementations fully maintain the contract established by the Object
class.
What I'm trying to get at here is that if you believe getClass()
is the only reliable way to preserve symmetry, you are probably using equals()
the wrong way.
Sure, it's easy to use getClass()
to preserve the symmetry required of equals()
, but only because x.equals(y)
and y.equals(x)
are always false. Liskov substitutability would encourage you to find a symmetry-preserving implementation that can yield true
when it makes sense. If a subclass has a radically different notion of equality, is it really a subclass?
Answered By - erickson
Answer Checked By - Timothy Miller (JavaFixing Admin)