Deep copy of list with objects in Kotlin

后端 未结 4 1566
夕颜
夕颜 2020-12-18 19:22

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

4条回答
  •  离开以前
    2020-12-18 19:48

    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:

    constructor(otherA: ClassA) {
        this.prop1 = otherA.prop1
        this.prop2 = otherA.prop2
        ...
    } 
    

    and then add them one by one to the new list:

    list1.forEach { list2.add(Class(it)) }
    

提交回复
热议问题