Junior — Middle
When is it recommended to implement the equals() method in a class?
sobes.tech AI
Answer from AI
The equals() method in a class is recommended to be implemented when objects of this class need to be compared not by reference (the default behavior), but by content — that is, by the value of fields.
This is important if:
- The class represents an entity with a logical sense of equality (for example, a user, a product).
- Objects will be used in collections where correct equality checking is important, such as in
HashSet,HashMap.
Example implementation of equals() and hashCode() for the Person class:
public class Person {
private String name;
private int age;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
If equals() is not overridden, object comparison will be by reference, which often does not match business logic.