EqualsBuilder & HashCodeBuilder

About

Java classes often override the equals() and hashCode() methods to define custom object equality and ensure correct behavior in collections (like HashMap, HashSet, etc.).

Apache Commons Lang provides utility classes — EqualsBuilder and HashCodeBuilder — to:

  • Simplify implementation of these methods

  • Avoid common mistakes

  • Improve readability and consistency

These builders use reflection or explicit field appending, supporting both shallow and deep comparisons.

Maven Dependency & Import

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version> <!-- or latest -->
</dependency>
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

1. EqualsBuilder

Purpose

Helps implement the equals(Object other) method in a clean and consistent way by comparing multiple fields.

Key Methods

Method
Description

append(field1, field2)

Appends field-by-field comparison

isEquals()

Returns final comparison result (true or false)

reflectionEquals(obj1, obj2)

Compares all fields via reflection

Example – Manual Field Comparison

Example – Reflection-Based Comparison

Reflection-based comparison includes all non-static, non-transient fields. It is convenient but less performant and not recommended when performance is critical or field-level control is needed.

2. HashCodeBuilder

Purpose

Helps implement the hashCode() method by building a consistent hash from multiple fields.

Key Methods

Method
Description

append(field)

Adds the field to the hash calculation

toHashCode()

Returns the final hash code

reflectionHashCode(object)

Generates hash code via reflection

Example – Manual Field HashCode

Example – Reflection-Based HashCode

Like reflectionEquals(), reflectionHashCode() includes all non-static, non-transient fields and is less performant but convenient.

Why Use These Builders?

Concern
Plain Java
Apache Commons Builders

Verbosity

High (manual equals and hashCode)

Concise, easy to read

Null handling

Manual

Built-in

Consistency

Prone to error

Consistent and standard

Reflection option

Not available

Available with one line

Performance

Manual is slightly faster

Builders have minor overhead

Last updated