I have an address object that I want to create an equals method for. I could have made this quite simple by doing something like the following (shortened a bit):
You could do the following:
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Address other = (Address) obj;
return equals(this.getStreet(),other.getStreet())
&& equals(this.getStreetNumber(), other.getStreetNumber())
&& equals(this.getStreetLetter(), other.getStreetLetter())
&& equals(this.getTown(), other.getTown());
}
private boolean equals(Object control, Object test) {
if(null == control) {
return null == test;
}
return control.equals(test);
}
Java 7 introduced built-in support for this use case with the java.util.Objects class see: