Recipe for a high-quality “equals” method
1. Use the == to check if the argument is a reference to this object.
2. Use the instanceof operator to check if the argument has the correct type.
3. Cast the argument to the correct type.
4. For each “significant” field in the class, check if that field of the argument matches the corresponding field of this object.
5. Always override hashCode when you override equals.
6. Don’t substitute another type for Object in the equals declaration.
7. Write unit-test.
@Override
public boolean equals(Object obj) {
if(obj == this) {
return true;
}
if(!(obj instanceof Person)) {
return false;
}
Person p = (Person)obj;
return p.name.equals(name)
p.birthday.equals(birthday)
p.personNumber == personNumber;
}
Ref.”Effective Java” by Joshua Bloch
Enother example with hashCode and toString:
@Override
public boolean equals(Object obj) {
if (obj == null || !obj.getClass().isInstance(this)) {
return false;
}
Beregning b = (Beregning) obj;
return new EqualsBuilder()
.append(simulertPensjon, b.getSimulertPensjon())
.append(linjer.size(), b.getLinjer().size()).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(simulertPensjon).append(linjer).hashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("simulertPensjon", simulertPensjon)
.append("antall linjer", linjer.size()).toString();
}