我有一个帐户列表,长按时,我要从arraylist中删除该项目。我正在尝试将其从Alertdialog中删除,但是我正在获取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
希望这能回答您的问题,祝您有美好的一天
编辑:您可以在此处找到其他说明,即使它是Java代码,问题也相同。
编辑n°2 leonardkraemer的答案向您展示了一种更为科特林友好的方法
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句