I´ve often found an equals method in different places. What does it actually do? Is it important that we have to have this in every class?
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;
}
}
It redefines “equality” of objects.
By default (defined in
java.lang.Object), an object is equal to another object only if it is the same instance. But you can provide custom equality logic when you override it.For example,
java.lang.Stringdefines equality by comparing the internal character array. That’s why:Even though you may not need to test for equality like that, classes that you use do. For example implementations of
List.contains(..)andList.indexOf(..)use.equals(..).Check the javadoc for the exact contract required by the
equals(..)method.In many cases when overriding
equals(..)you also have to overridehashCode()(using the same fields). That’s also specified in the javadoc.