Junior — Middle
Can you explain the concept of the equals method and its role in object comparison?
sobes.tech AI
Answer from AI
The equals method in Java is used to compare objects for equality based on content, not reference. By default, the equals method in the Object class compares references (i.e., checks if variables point to the same object).
Implementing a custom equals allows defining that two objects are considered equal if their internal fields match in value.
For example, for a Person class, you might compare the name and age:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person other = (Person) obj;
return age == other.age && Objects.equals(name, other.name);
}
The role of equals is important when working with collections, such as in HashSet or HashMap, where defining object equality affects the correctness of data structures.