0

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
Magesh Pandian
  • 8,789
  • 12
  • 45
  • 60

2 Answers2

1

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • thanks, But this one also like iteration right?, If list have thousand of data then its take more time to map. – Magesh Pandian Nov 30 '18 at 09:50
  • Yes. But as I said, you _have_ to iterate over the list to make a copy (or to do nearly anything else). So to avoid iteration, avoid copying the list in the first place. And "thousands" is a pretty small list, unless your objects are themselves very large. – Alexey Romanov Nov 30 '18 at 10:10
  • Thanks for the detail explanation. Is any way to achieve without using map or mapTo ? and one more thing i tired with mapTo and map both take's 4 millisec for 100 items and iterate 100 times – Magesh Pandian Nov 30 '18 at 12:55
0

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

Deepan
  • 124
  • 1
  • 10