我經常在不同的地方發現一個equals方法。它實際上做了什麼?我們必須在每個班級都有這個重要嗎?equals(Object obj)做什麼?
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;
}
}
我假設你已經看過了很清楚的文檔:http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html [向下滾動到equals()作爲直接鏈接似乎不適用於commments]。 – NPE