Sobes.tech
Junior — Middle

Do czego służy metoda hashCode() w języku Kotlin?

sobes.tech AI

Odpowiedź od AI

Metoda hashCode() w Kotlin służy do uzyskania kodu hash obiektu — wartości całkowitej, która pomaga efektywnie przechowywać i wyszukiwać obiekty w kolekcjach takich jak HashMap czy HashSet.

Ważne jest, aby jeśli dwa obiekty są równe według metody equals(), to ich hashCode() również się zgadzały. Zapewnia to poprawne działanie struktur danych opartych na haszowaniu.

Przykład nadpisania hashCode() razem z equals():

data class User(val id: Int, val name: String)

// W klasie data hashCode i equals są automatycznie zaimplementowane

// Jeśli piszemy klasę ręcznie:
class Person(val id: Int, val name: String) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Person) return false
        return id == other.id && name == other.name
    }

    override fun hashCode(): Int {
        var result = id
        result = 31 * result + name.hashCode()
        return result
    }
}