Implement hashCode method
suggest changeorg.apache.commons.lang3.builder.HashCodeBuilder (Apache Commons Lang) can implement hashCode. The value to return is toHashCode(). That is the method the library documents. Do not return the builder's own hashCode() and assume every release treats it as the computed total.
Selecting the fields:
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
builder.append(field1);
builder.append(field2);
builder.append(field3);
return builder.toHashCode();
}
Using reflection:
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, false);
}
The boolean argument is testTransients. false ignores transient fields. Reflection uses setAccessible, which a security manager or a module boundary can reject. Fields used by equals still have to be included here.
Using reflection avoiding some fields:
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, "field1", "field2");
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents