Java rewrites equals and hashcode methods



This article introduces several methods of rewriting equals and hashcode.


  1. If two objects are equal, their hash code must be equal;
  2. However, if the hash code of the two objects are equal, the two objects may not be equal.


Use lombok’s comments

lombok-1.16.16.jar! /lombok/EqualsAndHashCode.class
such as

public class XXXDto {


Using apache’s Method

    public boolean equals(Object o) {
        return EqualsBuilder.reflectionEquals(this,o);

    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);

If it is generated only from all fields, the reflection method can be used

Objects method

Java’s own Objects have a hashcode method to generate from fields.