I am new to kotlin and I am trying to make a copy of a list of objects.The problem I am having is that when I change items in the new copy, the old list gets changed as well. This is the object:
class ClassA(var title: String?, var list: ArrayList<ClassB>, var selected: Boolean)
class ClassB(val id: Int, val name: String)
I tried doing this, but it doesn't work:
val oldList:ArrayList<ClassA>
val newList :ArrayList<ClassA> = ArrayList()
newList.addAll(oldList)
Use 'to' for iterate object
List -> toList()
Array -> toArray()
ArrayList -> toArray()
MutableList -> toMutableList()
Example:
print log:
That's bacause you are adding all the object references to another list, hence you are not making a proper copy, you have the same elements in two list. If you want diferents list and diferent references, you must clone every object in a new list:
This is not related to kotlin, when you are adding the objects from the old list to the new one, it add the reference to them (no createing a new object ), whats mean it just copying the address in the memory to the new list.
To fix this problem you should create a new instance for each object. you can create a copy constructor, for example:
and then add them one by one to the new list: