package org.kodejava.example.commons.lang;
public class ObjectEqualsDemo {
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.equals(book2) = " + book1.equals(book2));
System.out.println("book3.equals(book1) = " + book3.equals(book1));
}
}
package org.kodejava.example.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
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019