Junior — Middle
Why override or use the equals method in data classes?
sobes.tech AI
Answer from AI
The equals method in data classes is overridden for correct comparison of objects based on content rather than reference. By default, in Java (and Android), the equals method compares references to objects, meaning two different objects with the same fields are considered different.
Overriding equals allows:
- Comparing objects by the values of their fields.
- Using objects in collections such as
HashSetor as keys inHashMap, where correct equality checks are important.
Example of overriding equals and hashCode in a Kotlin data class (which does this automatically):
data class User(val id: Int, val name: String)
// equals and hashCode are already implemented based on id and name
If the class is not a data class, then equals and hashCode need to be implemented manually to avoid errors during comparison and when working with collections.