Junior — Middle
In which situations should the equals method be overridden in Java for correct object comparison?
sobes.tech AI
Answer from AI
The equals method in Java should be overridden when you want to define your own criteria for object equality in your class, different from the standard reference comparison (which is implemented in Object).
This is especially important if objects of your class are considered equal logically when certain fields match, for example, in a Person class, objects are considered equal if the name and birth date match.
Overriding equals is necessary to:
- Correctly compare objects by content.
- Ensure proper operation of collections such as HashSet or HashMap, which use equals to determine the uniqueness of elements.
When overriding equals, it is also important to override hashCode to maintain the contract between these methods.
Example of overriding equals and hashCode:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return Objects.equals(name, person.name) && Objects.equals(birthDate, person.birthDate);
}
@Override
public int hashCode() {
return Objects.hash(name, birthDate);
}