collections - 如何在特定索引中添加新项目?
问题描述
我是 kotlin 的新手,我想更新列表中的项目。我使用这段代码:
var index: Int
for (record in recordList)
if (record.id == updatedHeader?.id) {
index = recordList.indexOf(record)
recordList.add(index, updatedHeader)
}
但它不能这样做,因为ConcurrentModificationException
解决方案
假设这recordList
是一个MutableList
和val
(所以,你想修改记录),你可以用它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
.
推荐阅读
- python - 我可以在 OneDrive / Sharepoint 中创建未过期的令牌吗?
- express - 使用 API 在 Vercel 上部署 Nuxt JS
- web-services - 您可以从 Google Places API 查询中返回多个营业地点吗?
- error-handling - 为什么不能用?(问号)直接在 Rust 中的 collect() 上?
- excel - 加快跨多个工作表VBA的复制/粘贴
- ide - 有没有办法锁定我使用 remix 制作的令牌?
- sql - 根据两列的比较获得最长的行集
- c++ - 线程1:EXC_BAD_ACCESS (code=1) error c++ project
- node.js - 尝试使用 postgres typeorm Raw 方法时出错
- c++ - 分别为数据成员和成员函数专门化模板