Junior — Middle
What methods are usually implemented in data classes in your experience?
sobes.tech AI
Answer from AI
In data classes on Android, the following methods are usually implemented:
- equals() — for comparing objects by content, not by reference.
- hashCode() — for proper operation with hash structures, such as HashMap.
- toString() — for convenient output of the object's content as a string.
- copy() (if using Kotlin) — for creating a copy of the object with the ability to modify some fields.
Example in Kotlin:
data class User(val id: Int, val name: String)
val user1 = User(1, "Alice")
val user2 = user1.copy(name = "Bob")
println(user1 == user2) // false
println(user1) // User(id=1, name=Alice)
If the class is written in Java, then usually equals(), hashCode(), and toString() are overridden manually to ensure correct comparison and convenient output.