我的老师给了我一个关于a等于覆盖示例的解决方案,如下所示:
@Override
public boolean equals(Object o)
{
if (this == o) return true;
boolean result = false;
if (o instanceof Product)
{
Product other = (Product)o;
result = this.id == other.id;
}
return result;
}
该方法被覆盖为Product类,其中具有每个产品唯一的属性id。但我不理解第一个if的意思,我认为第二个if已经检查了第一个if的限制。有人可以给我一个此代码工作的示例,以及下面这个代码不行的示例吗?谢谢!
@Override
public boolean equals(Object o)
{
boolean result = false;
if (o instanceof Product)
{
Product other = (Product)o;
result = this.id == other.id;
}
return result;
}
==
测试的原因是为了避免instanceof
迭代器和强制转换的类检查的双重开销。(但是,当它跟随一个instanceof
测试时,一些编译器会优化第二个开销。) - Ted Hopp