1

I know element cannot be duplicated in Set because i've seen a lot of documents about set. I wrote the following code to try experimenting it(element cannot be duplicated in set). I expect the code return "Person(name=person2)" but return " Person(name=person2) Person(name=person2) ". Why?

fun main(args : Array<String>) {
    var person1 = Person("person1")
    val person2 = Person("person2")
    val set = setOf(person1, person2)
    person1.name = "person2"
    for(s in set)
        println(s)
}
data class Person(var name : String)
himaru
  • 79
  • 6
  • 2
    Please see [this](https://stackoverflow.com/questions/4718009/mutable-objects-and-hashcode) – mightyWOZ Aug 16 '21 at 16:14
  • As per the linked question: **after storing an object in a set, map, &c, do not do anything that could change its hash code or equality behaviour**.  (The safest way is to make it immutable.)  Data structures are not designed to handle that, and it'll give undefined behaviour. (That could include the object seeming to disappear from the structure, appearing twice in different places, appearing and disappearing at different times or when accessed in different ways, or in extreme cases it could lead to an endless loop or crash.) – gidds Aug 16 '21 at 17:31

1 Answers1

3

The Set cannot continuously check items that have already been added to it to see if they have changed and may now be equal. It is generally discouraged to put mutable classes in a Set or to use them as Map keys, because it can lead to bugs that are easy to miss.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154