Collections 如何在特定索引中添加新项?
我是kotlin的新手,我想更新列表中的项目。 我使用以下代码:Collections 如何在特定索引中添加新项?,collections,kotlin,Collections,Kotlin,我是kotlin的新手,我想更新列表中的项目。 我使用以下代码: var index: Int for (record in recordList) if (record.id == updatedHeader?.id) { index = recordList.indexOf(record) recordList.add(index, updatedHeader) } 但是它不能做到这一点,因为Concu
var index: Int
for (record in recordList)
if (record.id == updatedHeader?.id) {
index = recordList.indexOf(record)
recordList.add(index, updatedHeader)
}
但是它不能做到这一点,因为
ConcurrentModificationException
假设recordList
是一个MutableList
和val
(因此,您希望在适当的位置修改记录),您可以使用forachedexed
查找您关心的记录并替换它们
这不会导致出现ConcurrentModificationException
:
recordList.forEachIndexed { index, record ->
if(record.id == updatedHeader?.id) recordList[index] = updatedHeader
}
val iterator = recordList.listIterator()
for (record in iterator) {
if (record.id == updatedHeader.id) {
iterator.previous() // move to the position before the record
iterator.add(updatedHeader) // prepend header
iterator.next() // move next, back to the record
}
}
另一方面,如果将recordList
重新定义为不可变列表和变量,则可以使用map
重写整个列表:
recordList = recordList.map { if(it.id == updatedHeader?.id) updatedHeader else it }
当然,如果您想将
列表
转换为可变列表
,如果列表中有一条记录具有给定的id
,您可以在该列表的末尾调用.toMutableList()
,找到其索引并在该索引处添加标题:
val index = recordList.indexOfFirst { it.id == updatedHeader.id }
if (index >= 0)
recordList.add(index, updatedHeader)
如果有多个具有给定id的记录,并且您希望在每个记录前面添加标题,则可以使用getlistIterator
,并使用其方法在迭代过程中修改列表,而无需获取ConcurrentModificationException:
recordList.forEachIndexed { index, record ->
if(record.id == updatedHeader?.id) recordList[index] = updatedHeader
}
val iterator = recordList.listIterator()
for (record in iterator) {
if (record.id == updatedHeader.id) {
iterator.previous() // move to the position before the record
iterator.add(updatedHeader) // prepend header
iterator.next() // move next, back to the record
}
}
具有指定的
id
的记录在列表中是否唯一?我是否正确地认为您希望在具有匹配id的记录之前预加标题?