我有一个帐户列表,当我长按时,我想从数组列表中删除该项目。我试图从警报对话框中删除它,但我得到了 ConcurrentModificationException。这是崩溃的地方:
listAccounts.forEachIndexed { index, account ->
if (idParamether == account.id) {
listAccounts.remove(account)
}
}
最佳答案
这是 JVM 的一个常见问题,如果你想在迭代时从集合中删除一个项目,你需要使用 Iterators
示例:
val myCollection = mutableListOf(1,2,3,4)
val iterator = myCollection.iterator()
while(iterator.hasNext()){
val item = iterator.next()
if(item == 3){
iterator.remove()
}
}
这将避免 ConcurrentModificationExceptions
我希望这回答了你的问题,祝你有美好的一天
编辑:你可以找到另一种解释here ,即使是Java代码问题都是一样的
Edit n°2 leonardkraemer 的 anwser 向您展示了一种对 kotlin 更友好的方式
关于kotlin - 如何避免 ConcurrentModificationException kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50032000/