Unable to delete item in mutable set if modified in Kotlin

I have a problem when using removeAll(), some objects cannot be deleted properly.

data class Dog(var name: String)

val dog1 = Dog(name = "dodo")
val dog2 = Dog(name = "mimi")

val set = mutableSetOf<Dog>()
set.add(dog1)
set.add(dog2)

dog1.name = "dodo2"

val before_size = set.size // 2

set.removeAll { true }

val after_size = set.size  // why it is 1!?, I expect it should be 0

removeAlldidn't work as i expected. There is another element in the mutable set. Any idea?

+4
source share
2 answers

Javadoc Set:

Note. Great care should be taken if mutable objects are used as specified elements. The behavior of the set is not indicated if the value of the object changes in a way that affects equal comparisons when the object is an element in the set.

By writing

dog1.name = "dodo2"

you did just that, you changed the object in a way that affects comparisons equals. In particular, using the construction

set.removeAll { true }

LinkedHashSet, , , , set.remove(it). it -, , , . LinkedHashSet - it.

+5

.

clear:

set.clear()

:

val dog1 = Dog(name = "dodo")
val dog2 = Dog(name = "mimi")

dog1.name = "dodo2"
val set = mutableSetOf(dog1, dog2)
+1

Source: https://habr.com/ru/post/1695744/


All Articles