Use EqualsBuilder and HashCodeBuilder to generate hashcode and equal methods

Automated hashCode () and equals ()

  problems: when the need to automatically implement hashCode () and equals () method

  solution: use EqualsBuilder and HashCodeBuilder

  use examples:

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:

1. In the above example, when the firstname and lastname are the same, the hashCode of the two objects is the same, so equals () returns true.

If the hashCode depends on all the filed of the class, you need to use the reflection mechanism to generate hashCode.

public int hashCode( ) { 
    return HashCodeBuilder.reflectionHashCode(this); 
} 


Like ToStringBuilder and HashCodeBuilder, EqualsBuilder also uses append () method for configuration. EqualsBuilder's append () method can accept basic types, objects, and arrays as parameters. The power of EqualsBuilder is that you can directly pass the array as a parameter to the append () method. EqualsBuilder will compare each element in the array in turn.

2. If two objects are equal if and only if each attribute value is equal, this sentence can be realized by the following code:

public boolean equals(Object o) { 
    return EqualsBuilder.reflectionEquals(this, o); 
}
Published 65 original articles · Like 16 · Visits 10,000+

Guess you like

Origin blog.csdn.net/s_156/article/details/105417194