Java如何使用Apache Commons实现hashCode和equals方法?
此代码段向您展示了如何使用ApacheCommonsLang库中的HashCodeBuilder和EqualsBuilder类来实现对象的hashCode()和equals()方法。要使用这两个类,我们只需要创建这些类的实例,并附加将使用计算哈希码并测试是否相等的属性即可。
hashCode()首先通过创建hashCode()方法来实现该方法。添加@Override注释,以确保我们已覆盖正确的方法。然后,我们创建一个HashCodeBuilder实例。附加我们将用于计算哈希码的字段。实际哈希码的最终结果可以通过toHashCode()从实例调用来获得HashCodeBuilder。
/** * Implement the hashCode method using HashCodeBuilder. */ @Override public int hashCode() { return new HashCodeBuilder().append(id).append(name).toHashCode(); }
我们做同样的事情来创建equals()方法。首先创建方法,它采用的单个参数类型java.lang.Object。添加@Override批注以确保我们重写正确的方法。在第一行,您可以检查传递的对象是否是同一对象的实例,我们使用instanceof运算符。然后,我们使用EqualsBuilder该类比较存储在两个对象中的值。为了获得相等的结果,您必须记住调用该isEquals()方法。
/** * Implement the equals method using the EqualsBuilder. */ @Override public boolean equals(Object obj) { if (!(obj instanceof DummyUser)) { return false; } DummyUser that = (DummyUser) obj; return new EqualsBuilder().append(this.id, that.id) .append(this.name, that.name).isEquals(); }
这是代码段的完整外观。
package org.nhooo.example.commons.lang; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; public class DummyUser { private Long id; private String name; /** * Constructor to create an instance of this class. */ public DummyUser() { } public static void main(String[] args) { DummyUser user1 = new DummyUser(); user1.setId(10L); user1.setName("Carol"); DummyUser user2 = new DummyUser(); user2.setId(10L); user2.setName("Carol"); System.out.println("user1.hashCode() = " + user1.hashCode()); System.out.println("user2.hashCode() = " + user2.hashCode()); System.out.println("user1.equals(user2) = " + user1.equals(user2)); } // Getters & Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * Implement the hashCode method using HashCodeBuilder. */ @Override public int hashCode() { return new HashCodeBuilder().append(id).append(name).toHashCode(); } /** * Implement the equals method using the EqualsBuilder. */ @Override public boolean equals(Object obj) { if (!(obj instanceof DummyUser)) { return false; } DummyUser that = (DummyUser) obj; return new EqualsBuilder().append(this.id, that.id) .append(this.name, that.name).isEquals(); } }
我们的代码的结果是:
user1.hashCode() = 64902380 user2.hashCode() = 64902380 user1.equals(user2) = true
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>