java.lang.Object

Implementing "equals", "hashCode", "toString" using Apache Commons

If we need to quickly implement methods "equals", "hashCode" and "toString" to a new class, the easiest solution is to use the Apache Commons library. Here is an example. Let's suppose we have the following object:

public class MyClass {

    int id;

    String value;

    ...  // some methods

}

Here is how we implement methods "equals", "hashCode", "toString" using tools from Apache Commons:

import org.apache.commons.lang3.builder.*;

public class MyClass {

    int id;

    String value;

    ...  // some methods

    @Override
    public boolean equals(Object object) {
        if (!(obj instanceof MyClass)) {
            return false;
        }
        MyClass that = (MyClass) object;
        return new EqualsBuilder()
         .append(this.id, that.id)
         .append(this.value, that.value)
         .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder()
         .append(id)
         .append(value)
         .toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
         .append("id", id)
         .append("value", value)
         .toString();
    }

}

We can use the same system regardless of the number and type of the fields. Just provide all the fields in the respective "append" methods.


Links:

Commons Lang at Apache Commons
A library providing useful methods for String manipulation et cetera.

viliam@bur.sk