本示例将向您展示如何使用类实现equals()andhashCode()对象java.util.Objects。的Objects类别提供一组实用的方法来工作,对象,如比较是否相等两个对象和计算的哈希码。其他方法包括对象null检查方法,对象到字符串方法等。
为了演示equals()和hash()方法,我们将创建一个简单的POJO Student,它具有id,name和等几个属性dateOfBirth。
package org.nhooo.example.util; import java.time.LocalDate; import java.util.Objects; public class Student { private Long id; private String name; private LocalDate dateOfBirth; public Student() { } public Student(Long id, String name, LocalDate dateOfBirth) { this.id = id; this.name = name; this.dateOfBirth = dateOfBirth; } 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; } public LocalDate getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(LocalDate dateOfBirth) { this.dateOfBirth = dateOfBirth; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student that = (Student) o; return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name) && Objects.equals(this.dateOfBirth, that.dateOfBirth); } @Override public int hashCode() { return Objects.hash(id, name, dateOfBirth); } }
在类中使用Objects.equals()和Objects.hash()方法Student可使equals()方法和hashCode()方法的实现简洁,易于阅读和理解。该Objects实用类将在这意味着它会检查对象的空场空安全的方式进行操作。
下面的代码片段将演示Student类的用法。它将使用该equals()方法比较对象并打印出对象的计算出的哈希码。
package org.nhooo.example.util; import java.time.LocalDate; import java.time.Month; public class EqualsHashCodeExample { public static void main(String[] args) { Student student1 = new Student(1L, "Alice", LocalDate.of(1990, Month.APRIL, 1)); Student student2 = new Student(1L, "Alice", LocalDate.of(1990, Month.APRIL, 1)); Student student3 = new Student(2L, "Bob", LocalDate.of(1992, Month.DECEMBER, 21)); System.out.println("student1.equals(student2) = " + student1.equals(student2)); System.out.println("student1.equals(student3) = " + student1.equals(student3)); System.out.println("student1.hashCode() = " + student1.hashCode()); System.out.println("student2.hashCode() = " + student2.hashCode()); System.out.println("student3.hashCode() = " + student3.hashCode()); } }
这是上面代码片段的结果:
student1.equals(student2) = true student1.equals(student3) = false student1.hashCode() = 1967967937 student2.hashCode() = 1967967937 student3.hashCode() = 6188033
实现equals()andhashCode()方法的另一种方法是使用Apache Commons Lang库。它的示例可以在这里看到:如何使用Apache Commons实现hashCode和equals方法?