Junior — Middle
Kas võib kasutada muudetavate omadustega andmeklassi võtmena hajutustabelis?
sobes.tech AI
Vastus AI-lt
It is not recommended to use a data class with mutable properties as a key in a hash table. Keys in hash tables should be immutable because changing the properties of an object involved in hash code calculation or comparison can lead to losing access to the element.
For example, if a property of the data class changes, affecting hashCode or equals, the object will no longer be found in the hash table:
data class User(var id: Int, var name: String)
val map = hashMapOf<User, String>()
val user = User(1, "Alice")
map[user] = "Developer"
user.name = "Bob" // Change property
println(map[user]) // Might return null, as hashCode has changed
Therefore, it is better to use immutable objects or keys with immutable properties.