Issue
So the problem is that after I add All items to my new arrayList2 and change something in arrayList1 it makes the same change in arrayList2. My goal is to basically clone all items from arraylist1 and after I change something in it, items in arraylist2 remain the same as after addAll command. Example of my encounter challenge:
arraylist2.addAll(arrayList1)
arraylist2[0].arrayCoordinates // [0, 0]
arraylist1[0].arrayCoordinates = arrayOf(1, 1)
arraylist2[0].arrayCoordinates // [1, 1]
Thanks for the help in advance.
Solution
To solve this problem I did a deep copy of the list. Copied using data class command copy.
sectionsSortedFinal = sectionsSorted.map { it.copy() } as ArrayList<CutomObj>
but unfortunately, this command does not deep copy entirely. For example, I have a data class.
data class User(val name: String, val age: Int, val namesOfCarsOwned: ArrayList<String>)
It will only deep copy name and age. To solve this issue a custom copy function needs to be made inside of class:
fun copy(name: String = this.name,
age: Boolean = this.age,
grammarSuggestions: ArrayList<String> = ArrayList(this.grammarSuggestions))
= User(name, age, grammarSuggestions)
Answered By - AverageLinuxEnjoyer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.