首页 > 解决方案 > 如何在特定索引中添加新项目?

问题描述

我是 kotlin 的新手,我想更新列表中的项目。我使用这段代码:

var index: Int
    for (record in recordList)
        if (record.id == updatedHeader?.id) {
            index = recordList.indexOf(record)
            recordList.add(index, updatedHeader)
        }

但它不能这样做,因为ConcurrentModificationException

标签: collectionskotlin

解决方案


假设这recordList是一个MutableListval(所以,你想修改记录),你可以用它forEachIndexed来找到你关心的记录并替换它们。

这并没有导致ConcurrentModificationException

recordList.forEachIndexed { index, record -> 
    if(record.id == updatedHeader?.id) recordList[index] = updatedHeader
}

另一方面,如果您重新定义recordList为非可变列表和 var,则可以使用以下命令重写整个列表map

recordList = recordList.map { if(it.id == updatedHeader?.id) updatedHeader else it }

当然,.toMutableList()如果你想把你的List变成MutableList.


推荐阅读