Junior — Middle
When is it advisable to implement a custom equals() method in data classes?
sobes.tech AI
Answer from AI
It is advisable to implement a custom equals() method in data classes when you need to determine that two objects are considered equal in terms of their content, not just by reference in memory.
This is important if:
- The class contains fields that logically define equality (e.g., identifier, property values).
- Objects are used in collections where comparison affects behavior (e.g., in
HashSet,HashMap). - You need to compare the contents of objects, not their addresses.
Example:
public class User {
private String id;
private String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id.equals(user.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}
Here, two User objects are considered equal if their id matches. This allows correct operation with collections and comparisons.