Home > Back-end >  How to avoid remove item from second list affects the original list in kotlin
How to avoid remove item from second list affects the original list in kotlin

Time:11-04

What I am trying to do is keep an original list and two duplicated ones in which to perform operations. Say orginalList is a list of String and has 5 entries

duplicatedList = originalList
secondDuplicatedList = orignalList
duplicatedList.remove(0)
secondDuplicatedList.remove(1)

The values are removed from all three lists and at the end all three lists will have 3 entries.

I have seen a lot of similar questions, but I do not quite get it

Any help or suggestion would be great. thanks

CodePudding user response:

duplicatedList = originalList

Using equal sign will make another pointer to the same location in memory (duplicatedList is not instantiated from scratch); so both duplicatedList & originalList points to the same list

Instead, you need to create a brand new list in memory with the same values of the original list.

You can use the Collection's extension function toMutableList() to do that:

duplicatedList = originalList.toMutableList()
secondDuplicatedList = originalList.toMutableList()

This extension function originally creates a new list:

public fun <T> Collection<T>.toMutableList(): MutableList<T> {
    return ArrayList(this)
}

CodePudding user response:

try

duplicatedList.addAll(originalList)

  • Related