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?