为什么如果我在两个包装器对象上运行 .equals 方法,它将根据下面的 WrapperEqualsEquals 类返回 true但是(我强调但是)为什么我们需要在下面的 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;
}
}
}