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?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…