Equals () method in Java Baeldung


How to properly override equals() method in Java?


Basic principles when designing the equals method:

  1. Reflexivity: for any non-null objects x, x.equals(x) must return true .
  2. Symmetry: For any non-null objects x and y, x.equals(y) must return true if and only if y.equals(x) returns true .
  3. Transitivity: For any non-null objects x, y, and z, if x.equals (y) returns true and y.equals(z) returns true , then x.equals(z) must return true .
  4. Persistence: Repeated calls to the equals() method must return the same value until any value of the object's properties is changed. That is, if two objects are equal, then they will be equal as long as their properties remain unchanged.
  5. For any non-null x objects, x.equals(null) must return false .

It is also worth noting that the argument to the equals method is always an object of the Object class. For example, when overriding a method for the Person class, we must use the following signature: public boolean equals(Object person) . It is often a mistake for beginners to make a mistake and use the signature public boolean equals(Person person) , which leads to an overload of the equals method.

The equals method is related to the hashCode method: for identical objects, the value returned by the hashCode method must be the same. Therefore, both methods are often overridden.

Scroll to Top