Sobes.tech
Junior — Middle

What is the purpose of the equals method in the Any class?

sobes.tech AI

Answer from AI

The equals method in the Any class is used to compare the current object with another object for equality. In Android (and Java/Kotlin), this method is usually overridden to define the logic for comparing objects based on their content, not their reference. This is important for the correct functioning of collections and other data structures.

Example in Kotlin:

class Person(val name: String, val age: Int) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Person) return false
        return name == other.name && age == other.age
    }

    override fun hashCode(): Int {
        return name.hashCode() * 31 + age
    }
}