[英]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.