How do I implement hashCode() method using HashCodeBuilder class?

package org.kodejava.example.commons.lang;

public class ObjectHashCodeDemo {

    public static void main(String[] args) {
        Book book1 = new Book(1L, "Spring Boot in Action", "Craig Walls");
        Book book2 = new Book(2L, "Docker in Action", "Jeff Nickoloff");
        Book book3 = book1;

        System.out.println("book1.hashCode() = " + book1.hashCode());
        System.out.println("book2.hashCode() = " + book2.hashCode());
        System.out.println("book3.hashCode() = " + book3.hashCode());
package org.kodejava.example.commons.lang;

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


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

    public Book(Long id, String title, String author) { = id;
        this.title = title; = author;

    //~ Implements getters and setters here.

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

        if (!(o instanceof Book)) {
            return false;

        Book that = (Book) o;
        return new EqualsBuilder()
            .append(this.title, that.title)

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

    public int hashCode() {
        return new HashCodeBuilder()

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

Maven Dependencies

<!-- -->


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me, buy me ☕ or 🍵

Leave a Reply