1.6. Automating hashCode( ) and equals( )
Problem
You need a way to automatically
implement equals() and
hashCode( )
methods.
Solution
Commons Lang
EqualsBuilder
and
HashCodeBuilder
provide methods to automate both the equals( ) and
hashCode( ). Example 1-2 briefly
demonstrates these two builders using the
PoliticalCandidate bean from the previous two
recipes.
Example 1-2. Automating hashCode( ) and equals( )
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
public class PoliticalCandidate {
// Member variables - omitted for brevity
// Constructors - omitted for brevity
// get/set methods - omitted for brevity
// A hashCode which creates a hash from the two unique identifiers
public int hashCode( ) {
return new HashCodeBuilder(17, 37)
.append(firstName)
.append(lastName).toHashCode( );
}
// An equals which compares two unique identifiers
public boolean equals(Object o) {
boolean equals = false;
if ( o != null &&
PoliticalCandidate.class.isAssignableFrom(o) ) {
PoliticalCandidate pc = (PoliticalCandidate) o;
equals = (new EqualsBuilder( )
.append(firstName, ps.firstName)
.append(lastName, ps.lastName)).isEquals( );
}
return equals;
}
}Discussion
HashCodeBuilder has a constructor that takes two
integer primitives. These primitives are used as an offset when
creating a hash code; both numbers should be odd, nonzero, and prime.
The HashCodeBuilder in Example 1-2 is configured to use the
firstName and the lastName of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access