gpt4 book ai didi

collections - 如何在特定索引中添加新项目?

转载 作者:行者123 更新时间:2023-12-02 13:23:16 26 4
gpt4 key购买 nike

我是Kotlin的新用户,我想更新列表中的项目。
我使用以下代码:

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

但由于 ConcurrentModificationException,它无法执行此操作

最佳答案

假设recordListMutableListval(因此,您想在适当的位置修改记录),则可以使用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

关于collections - 如何在特定索引中添加新项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50321991/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com