How to properly override
equals() method in Java?
Basic principles when designing the
- Reflexivity: for any non-null objects x,
- Symmetry: For any non-null objects x and y,
trueif and only if
- Transitivity: For any non-null objects x, y, and z, if x.equals (y) returns
- 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.
- For any non-null x objects,
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 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.