Java Language Implement hashCode() method


Example

To implement the hashCode method of an object easily you could use the HashCodeBuilder class.

Selecting the fields:

@Override
public int hashCode() {
    
    HashCodeBuilder builder = new HashCodeBuilder();
    builder.append(field1);
    builder.append(field2);
    builder.append(field3);
    
    return builder.hashCode();
}

Using reflection:

@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this, false);
}

the boolean parameter indicates if it should use transient fields.

Using reflection avoiding some fields:

@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this, "field1", "field2");
}