Java rewrites equals and hashcode methods

  java

Order

This article introduces several methods of rewriting equals and hashcode.

Rules

  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.

Method

Use lombok’s comments

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

@ToString
@EqualsAndHashCode
public class XXXDto {

}

Using apache’s Method

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

    @Override
    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.

Objects.hash(mobile,name);