如何避免ConcurrentModificationException Kotlin

zasaz:

我有一个帐户列表,长按时,我要从arraylist中删除该项目。我正在尝试将其从Alertdialog中删除,但是我正在获取ConcurrentModificationException。这是崩溃的地方:

listAccounts.forEachIndexed { index, account ->
    if (idParamether == account.id) {
        listAccounts.remove(account)
    }
}
SeekDaSky:

这是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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Kotlin:大量的ConsPStack,如何避免?

如何使用Findbugs避免Kotlin文件

如何避免java.util.ConcurrentModificationException

如何避免或修复与 Int 与 Integer 相关的 Kotlin 警告

Kotlin:如何避免在构造函数中重复代码?

Kotlin:如何避免委派属性中的自动装箱(垃圾)?

如何避免 MutableStateFlow kotlin 中的默认值

如何避免Kotlin字段中的冗余null检查(FindBugs警告)

如何从到的ArrayLists移除对象时避免ConcurrentModificationException的”

迭代地图和更改值时如何避免ConcurrentModificationException?

迭代时如何仅在 ArrayList 中避免 ConcurrentModificationException?

避免TreeMap ConcurrentModificationException?

从C调用Kotlin回调函数时,如何避免在Kotlin Native中出现错误“ staticCFunction必须接受未绑定的...”?

如何延迟Kotlin Multiplatform(纯Kotlin)

Kotlin暴露:如何创建准备好的语句或避免SQL注入?

如何避免Kotlin中具有相同名称的类型冲突?

如何避免每次在build.gradle中添加插件'kotlin-adnroid-extensions'

在Kotlin中继承时避免冗余代码

如何获得Kotlin AST?

如何指定Kotlin版本?

如何摇动生成Kotlin?

Kotlin是如何专门编译的?

如何阅读 kotlin 注释

Kotlin SharedFlow - 如何订阅?

如何在并发线程中处理`values()`和`put()`时如何避免HashMap“ ConcurrentModificationException”?

在遍历和删除ArrayList中的元素时如何避免java.util.ConcurrentModificationException

如何在迭代时从“ ArrayList”中删除元素时避免“ ConcurrentModificationException”?

如何在JPA和Hibernate中合并实体时避免java.util.ConcurrentModificationException

如何在从LinkedList进行基于递归迭代器的删除时避免ConcurrentModificationException?