Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Collections 如何在特定索引中添加新项?_Collections_Kotlin - Fatal编程技术网

Collections 如何在特定索引中添加新项?

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

我是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
(因此,您希望在适当的位置修改记录),您可以使用
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的记录,并且您希望在每个记录前面添加标题,则可以使用get
listIterator
,并使用其方法在迭代过程中修改列表,而无需获取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的记录之前预加标题?