问题描述
我使用Eclipse来生成 .equals()
和 .hashCode()
标签为Use'instanceof'来比较类型的选项。默认情况是取消选中此选项,并使用 .getClass()
来比较类型。有什么理由我应该更喜欢 .getClass()
over instanceof
?
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
?
不使用 instanceof
:
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
使用 instanceof
:
if (obj == null)
return false;
if (!(obj instanceof MyClass))
return false;
我通常会查看 instanceof
选项,然后进入并删除 if(obj == null)
检查。 (这是多余的,因为空对象总是会失败 instanceof
。)是否有任何理由是一个坏主意?
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?
推荐答案
如果您使用 instanceof
,使您的等于
实现 final
将保留方法的对称合约: x.equals(y)== y.equals(x)
。如果 final
似乎是限制性的,请仔细检查您的对象等同性的概念,以确保您的覆盖实现完全维护由 Object
class。
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.
这篇关于任何理由在生成.equals()时,优先于getClass()over instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!