본문 바로가기
Programming

Kotlin - Respect the contract of hashCode

by 생각하는달팽이 2021. 10. 15.

아래 결과에 대해서 한번 생각해보자. hashTable 의 경우 hashCode 를 키로 설정한다.

/**
 * You can edit, run, and share this code. 
 * play.kotlinlang.org 
 */

data class FullName (
    var name : String,
    var surname : String
)

fun main() {
    val person = FullName("hello","world")
    val s = mutableSetOf<FullName>()
    s.add(person)
    person.surname = "Mosk"


    println(s.contains(person)) // false
    println(person in s) // false

    println(s.first() == person) // true

}

위의 결과가 나오는 부분이 잘 이해가 안된다면, hashCode 값을 찍어보면 알 수 있다.

/**
 * You can edit, run, and share this code. 
 * play.kotlinlang.org 
 */

// default : final
// open : 
// 
data class FullName (
    var name : String,
    var surname : String
)

fun main() {
    val person = FullName("hello","world")
    val s = mutableSetOf<FullName>()
    s.add(person)

    println(person.hashCode()) // -1107616512

    person.surname = "Mosk"

    println(person.hashCode()) // -1218531064
}

hashTable 은 데이터를 hashCode 키값에 의존하게된다. 그로인해, contains, in 과 같은 operation 들이, 실제 넘겨받는 person 객체의 변경된 hashCode 로 HashTable 의 키를 찾게 되는데, 이럴 경우, 기존 HashCode 에 Mapping 된 값을 불러오지 못한다. 그로인해서, 위의 결과가 나오게 된다. first() 의 경우, 키로 접근하는 것이아니라, 첫번째 값에 대해서 리턴하므로, true 라는 값을 얻을 수 있다.

반응형