How to copy or clone mutableList of data object without using collection map in Kotlin

4k Views Asked by At

I create copy of one MutableList. When I update element value of copy MutableList But Original List element value also changed. When I use map It working fine but It is like a iteration of whole list, Is any way to do achieve without iteration ? how to copy elements of the MutableList.

    val array: MutableList<UserData> = ArrayList()
    val userData = UserData("DataOne")
    array.add(userData)

    val arrayCopy = ImmutableList.copyOf(array)// not working
    //val arrayCopy = array.toMutableList()// not working
   // val arrayCopy = array.map { it.copy() }.toMutableList()//working

    Log.i("----> array ", array[0].name)//print DataOne
    Log.i("----> arrayCopy ", arrayCopy[0].name)//print DataOne

    arrayCopy[0].name = "DataTwo"
    Log.d("----> array ", array[0].name)//print DataTwo
    Log.d("----> arrayCopy", arrayCopy[0].name) //print DataTwo
2

There are 2 best solutions below

3
On

ImmutableList.copyOf does copy the list. The problem is that you want to copy elements of the list as well. Of course you have to iterate over the list to do that, but so does copyOf and I don't see why you expect it's possible to avoid. A slightly better version of map is

 array.mapTo(mutableListOf()) { it.copy() }

because it iterates only once.

0
On

Sorry but there wouldn't be any other way cause to convert one element you will have to read/copy it once, for n number of element you'll have to iterate n times to get the proper copy. The only other way I can think of is to create the desired immutable/mutable list in the first place and not copying it all at once later. Hope this helps