我看到了一个关于定义的代码段equals
,来自本论坛的另一个问题线程。但我的问题是以下代码的作用是什么,为什么需要它?谢谢。
if (obj == this)
{
return true;
}
原代码如下所示。http://stackoverflow.com/questions/8338326/what-does-equalsobject-obj-do#
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
if (obj == null)
{
return false;
}
if (obj instanceof Contact)
{
Contact other = (Contact)obj;
return other.getFirstName().equals(getFirstName()) &&
other.getLastName().equals(getLastName()) &&
other.getHomePhone().equals(getHomePhone()) &&
other.getCellPhone().equals(getCellPhone());
}
else
{
return false;
}
}
实施equals
Java类的方法是一个经常讨论的话题。一般来说,您要确保该方法返回true
, if:
- 你比较的对象
this
with 与指针相关的是同一个对象 (object == this) 或
- 你比较的对象
this
与您的域名相同
因此,关于你的问题,你询问前一种情况,其中 Java 只是检查是否object
通过了并且this
指向内存中的同一地址(也许此链接可以帮助您http://www.javaworld.com/article/2072762/java-app-dev/object-equality.html http://www.javaworld.com/article/2072762/java-app-dev/object-equality.html).
简短说明:当您实施equals
方法,您通常遵循以下模式:
-
检查您是否有相同的对象(关于指针),即
if (object == this) return true;
-
你确保你没有任何null
实例(以避免进一步NullPointerException
如果是null
它永远不可能相等,即
else if (object == null) return false;
-
您检查该对象是否与您的域中的 equal 含义相等(例如,如果id
是平等的);在进行特定于域的验证之前,您通常始终确保拥有正确实例的对象,即
else if (this.getClass().equals(obj.getClass()) { ... }
or
else if (this.getClass().isInstance(obj.getClass()) { ... }
-
在所有其他情况下你想返回 false,即
else return false;
NOTE:当实施equals
方法通常很有用,使用Objects.equals(...)
方法来比较实例的不同属性。
EXAMPLE:
@Override
public boolean equals(final Object obj) {
if (obj == this) {
// we have the same object regarding the pointers (e.g., this.equals(this)), or have a look at 'Manjunath M' post for a different example
return true;
} else if (obj == null) {
// we compare with null (e.g., this.equals(null))
return false;
} else if (Contact.class.isInstance(obj.getClass())) {
/*
* If you want to be more strict you could also use:
* getClass().equals(obj.getClass())
*/
Contact other = Contact.class.cast(obj);
return Objects.equals(other.getFirstName(), getFirstName()) &&
Objects.equals(other.getLastName(), getLastName()) &&
Objects.equals(other.getHomePhone(), getHomePhone()) &&
Objects.equals(other.getCellPhone(), getCellPhone());
} else {
return false;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)