在生成 .equals() 时,有什么理由更喜欢 getClass() 而不是 instanceof? [英] Any reason to prefer getClass() over instanceof when generating .equals()?

查看:30
本文介绍了在生成 .equals() 时,有什么理由更喜欢 getClass() 而不是 instanceof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Eclipse 生成 .equals().hashCode(),并且有一个标记为使用 'instanceof' 来比较类型"的选项.默认情况下此选项未选中并使用 .getClass() 来比较类型.有什么理由让我更喜欢 .getClass() 而不是 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,让你的 equals 实现 final 将保留该方法的对称契约:x.equals(y) == y.equals(x).如果 final 看起来有限制,请仔细检查您的对象等效概念,以确保您的覆盖实现完全维护由 Object 类建立的契约.

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() 而不是 instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆