![](/img/trans.png)
[英]Why doesn't this equals method properly override the object.equals method?
[英]Override equals method properly
我的老师给了我一个等于重写的例子的解决方案,它是这样的:
@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。 但我不明白第一个的意思,我认为第二个如果已经检查了第一个的限制。 任何人都可以给我一个这个代码工作的例子,下面这个没有? 谢谢!
@Override
public boolean equals(Object o)
{
boolean result = false;
if (o instanceof Product)
{
Product other = (Product)o;
result = this.id == other.id;
}
return result;
}
这两个代码示例都有效。 if (this == o) return true;
在第一个示例中,性能优化(最可能是过早优化 - 始终是首先配置) ,它检查对象是否与自身进行比较。 在Java中, ==
运算符比较两个对象是否是同一个实例,而不是它们是否是具有相同数据的不同实例。
有可能写出equals方法的风格。 以下是我通常的做法:
public boolean equals(Object obj) {
if (obj instanceof Product) {
Product that = (Product) obj;
return this.id == that.id;
}
return false;
}
如果我知道我的代码永远不会将对象与其他类型的对象进行比较,或者反对null,那么我甚至可以编写如下所示的代码,这样如果反正它会抛出异常 - 这意味着我的代码有一个错误,所以通过提前失败,我会发现它并尽快修复它。
public boolean equals(Object obj) {
Product that = (Product) obj;
return this.id == that.id;
}
你是对的。 第一个if语句是多余的,因为this == o
暗示o instanceof Product
和this.id == other.id
。
如果论证是性能,我会说它过早地优化了。
if (this == o) return true;
上述陈述是多余的。
更具体地说,它只是检查你是否正在将一个对象与它自己进行比较......所以它可以跳过它下面的代码。 例如:
Foo f = new Foo();
f.equals(f); //the if (this == o) would be true. References the same thing.
注意:顺便说一句,如果一个覆盖等于,则应覆盖hashcode()以维护hashcode()的一般契约 - 相等的对象必须具有相同的哈希码(反之则不正确,因为两个对象可能具有相同的哈希但不是等于。)
http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object )
在eclipse中你可以选择“生成hashCode()和equals()...”(菜单源代码)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.