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)

推荐答案

这是因为您正在将所有对象引用添加到另一个列表中,因此您没有制作正确的副本,两个列表中有相同的元素.如果需要不同的列表和不同的引用,则必须克隆新列表中的每个对象:

public data class Person(var n: String)

fun main(args: Array<String>) {
    //creates two instances
    var anna = Person("Anna")
    var Alex =Person("Alex")

    //add to list
    val names = arrayOf(anna , Alex)
    //generate a new real clone list
    val cloneNames = names.map{it.copy()}

    //modify first list
    cloneNames.get(0).n = "Another Anna clone"

    println(names.toList())
    println(cloneNames.toList())
}

[Person(n=Anna), Person(n=Alex)]
[Person(n=Another Anna clone), Person(n=Alex)]

Kotlin相关问答推荐

Kotlin -从列表中获取特定过滤器的唯一列表值

有没有一种简单的方法来识别物体?

如何将消费者放入 Kotlin 的 map 中?

Ktor 在 Heroku 上的 CORS 问题,但在本地没有

始终抛出的函数 - 具有块主体的函数中需要的返回表达式

Kotlin 中的 maxOf() 和 max() 方法有什么区别?

Kotlin 可空泛型

Kotlin Path.useLines { } - 如何不获取 IOException("Stream closed")?

Jetpack Compose 中的连续重组

Kotlin 条件格式字符串

如何从 kotlin 函数中 Select 正确的枚举值

Kotlin 中获取类简单名称的最佳实践

Kotlin 静态函数:伴生对象,@JvmStatic @JvmField

如何在 Kotlin 中使用 volatile

如何从定义它们的类外部调用扩展方法?

Kotlin 顶级函数与对象函数

Kotlin使用运行时断言进行空判断?

使用范围的稀疏sparse值列表

从命令行运行Java到Kotlin转换器?

如何在Android Studio 4.1中默认启用Kotlin Android扩展