How do I implement hashCode() method using Commons Lang?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import java.io.Serializable;

public class BookEqualsExample implements Serializable {
    private Long id;
    private String title;
    private String author;

    //~ Implements getters and setters here.

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof BookEqualsExample)) {
            return false;
        }

        BookEqualsExample that = (BookEqualsExample) o;
        return new EqualsBuilder()
                .append(this.id, that.id)
                .append(this.title, that.title)
                .append(this.author, that.author)
                .isEquals();

        // You can also use reflection of the EqualsBuilder class.
        // return EqualsBuilder.reflectionEquals(this, that);
    }

    public int hashCode() {
        return new HashCodeBuilder()
                .append(id)
                .append(title)
                .append(author)
                .toHashCode();

        // Or even use the simplest method using reflection
        // below.
        // return HashCodeBuilder.reflectionHashCode(this);
    }
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply