[英]Wrapper objects and equality
為什么會出現這樣的情況:如果我在兩個包裝器對象上運行.equals方法,它將按照下面的WrapperEqualsEquals類返回true, 但是 (並且我強調but)為什么我們需要在下面的Blob類中覆蓋equals方法使其返回true。 基本上,為什么包裝器對象不得不重寫.equals方法而逃脫了?
class WrapperEqualsEquals
{
public static void main(String []args)
{
Integer one=new Integer(1);
Integer oneB=new Integer(1);
System.out.println(one == oneB);
System.out.println(one.equals(oneB));
}
class OverrideEquals
{
public static void main (String [] args)
{
Blob a= new Blob(1,"a");
Blob b= new Blob(1,"a");
System.out.println(a==b);
System.out.println(a.equals(b));
}
class Blob
{
int blobNumber;
String blobText;
Blob(int blobNumber,String blobText)
{
this.blobNumber=blobNumber;
this.blobText=blobText;
}
//"overriding" the 'equals' method
public boolean equals (Object o)
{
if (o instanceof Blob)
{
Blob o2=(Blob)o;
return ((o2.blobNumber==this.blobNumber) &&(o2.blobText==this.blobText))?
true:false;
}
else
{
return false;
}
}
}
默認情況下,僅當隱式和顯式參數的哈希碼相等時,Object#equals(Object)才返回true。 因為您創建了兩個單獨的Blob對象,所以它們不會指向相同的引用(按照hashCode()),因此, 除非覆蓋.equals方法, 否則它們將不相等。 但是,根據Java約定,僅當兩個對象的哈希碼相等時,.equals才應返回true,因此您也可能希望覆蓋hashCode。 這還將保留內存使用情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.