Java如何使用HashCodeBuilder类实现hashCode()方法?
package org.nhooo.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.nhooo.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; } //〜在这里实现获取器和设置器。 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(); //您还可以使用EqualsBuilder类的反射。 //返回EqualsBuilder.reflectionEquals(this,that); } public int hashCode() { return new HashCodeBuilder() .append(id) .append(title) .append(author) .toHashCode(); //甚至使用最简单的反射方法 //下面。 //返回HashCodeBuilder.reflectionHashCode(this); } }
Maven依赖
<!-- 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>