Home > database >  Kotlin list on editing a item after adding the changes are replicated in added list
Kotlin list on editing a item after adding the changes are replicated in added list

Time:01-03

I have created a data class and added into list, same item is added multiple times in a list, if I change a value of the item and it is replicated in the items that are added in a list.

data class Boy(var name : String, var age : Int)

    fun main() {
        var boysList = arrayListOf<Boy>()
        var boysListFinal = arrayListOf<Boy>()
        val boy1 = Boy("test1234",1)
        boysList.add(boy1)
        for(boy in boysList){
            boysListFinal.add(boy)
            boysListFinal.add(boy)
            boysListFinal.add(boy)
            boy.name = "test1"
            boysListFinal.add(boy)
        }
        println(boysListFinal)
    }

Output

[Boy(name=test1, age=1), Boy(name=test1, age=1), Boy(name=test1, age=1), Boy(name=test1, age=1)]

Expected output

[Boy(name=test1234, age=1), Boy(name=test1234, age=1), Boy(name=test1234, age=1), Boy(name=test1, age=1)]

I have tried by assigning the item to a object still I cannot get the expected output

fun main() {
    var boysList = arrayListOf<Boy>()
    var boysListFinal = arrayListOf<Boy>()
    val boy1 = Boy("test1234",1)
    boysList.add(boy1)
    for(boy in boysList){
        boysListFinal.add(boy)
        boysListFinal.add(boy)
        boysListFinal.add(boy)        
        val boy2 = boy
        boy2.name = "test1"
        boysListFinal.add(boy2)
    }
    println(boysListFinal)
}

CodePudding user response:

When you put the same item several times into the list, all changes to that item will be visible on all occurrences in the list, because it is always pointing to that same item.

The declaration of variable boy2 does not produce another Boy, but it is only another reference to the same boy.

You can use the copy function of data classes to produce a copy of your object:

val boy2 = boy.copy(name = "test1")
boysListFinal.add(boy2)

CodePudding user response:

This is the expected behaviour.

The important thing to note is that you are only creating one instance of the Boy class, because you call the constructor Boy(...) only once. You're never making any copies of it either (which you could do using the copy(..) method that was generated for the Boy class because it's a data class).

So there is effectively only one Boy in the whole program. When you assign that instance to variables, or when you add it to a list, you're only setting a reference to that same object, so you have many different places that "point to" the same object in memory. If you mutate a property of that object, any place that references the object will see the change.

  • Related