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

package org.kodejava.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.commons.lang;

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

import java.io.Serializable;

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

    public Book(Long id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = 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.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

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.