Q:What issues should be considered when overriding equals and hashCode in Java?

D: What issues / pitfalls must be considered when overriding equals and hashCode?

Test Case #3


File ID: #27609-9-cc


@Override
public boolean equals(Object o) {
    if (this = = o) return true;
    if (!(o instanceof Person)) return false;
    Person person = (Person) o;
    EqualsBuilder equalsBuilder = new EqualsBuilder();
	// if deriving: appendSuper(super.equals(obj)).
    equalsBuilder.append(id, person.id);
    equalsBuilder.append(name, person.getName());
    return equalsBuilder.isEquals();
}
@Override
public int hashCode() {
    HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();
	// if deriving: appendSuper(super.hashCode()).
    hashCodeBuilder.append(id);
    hashCodeBuilder.append(name);
    return hashCodeBuilder.toHashCode();
}

  1. Granted, that was a bit superfluous statement (following the style of the original javadoc for Object.equals(): "For any non-null reference value x, x.equals(null) should return false"")
  2. Additional point about appendSuper(): you should use it in hashCode() and equals() if and only if you want to inherit the equality behavior of the superclass. For instance, if you derive straight from Object, there's no point because all Objects are distinct by default.
  3. You can get Eclipse to generate the two methods for you: Source > Generate hashCode() and equals().

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: