android - 修改 SnapshotStateList 会抛出 ConcurrentModificationException

标签 android kotlin concurrentmodification

SnapshotStateList 的文档指出它类似于常规的可变列表。我有一个用例,我需要修改列表中的所有元素 (set case)。这不会改变列表的大小,但我遇到了 ConcurrentModificationException。

我在这里创建了一个非常简化的用例版本。以下 kotlin 列表工作正常:

val myList2 = mutableListOf("a", "b", "c")
myList2.forEachIndexed { index, _ ->
    // Modify item at index
    myList2[index] = "x"
}

但是我在这里得到一个并发修改异常:

val myList = mutableStateListOf("a", "b", "c")
myList.forEachIndexed { index, _ ->
    // Modify item at index but I get an exception
    myList[index] = "x"
}

如何就地修改 mutableStateList() 的所有元素而不会出现并发修改异常?

编辑:

我可以创建一个 mutableStateList 的副本来迭代哪个工作正常但是因为我没有改变列表的大小,是否可以就地进行?

最佳答案

一些可能的解决方法是使用 replaceAll 就地转换列表(只要您不需要索引),或者如果您需要,只需对索引使用老式循环

val listA = mutableListOf("A","B","C")

// this works
listA.forEachIndexed { i, s ->
    listA[i] = s.lowercase()
}

val listB = mutableStateListOf("A","B","C")

// this fails - as you noted
listB.forEachIndexed { i, s ->
    listB[i] = s.lowercase()
}

// this works, as long as you don't need the index
listB.replaceAll { s -> s.lowercase() }

// this also works, and lets you have the index
for(i in listB.indices) {
    listB[i] = listB[i].lowercase()
}

关于android - 修改 SnapshotStateList 会抛出 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70457309/

相关文章:

android - 如何查看 Jetpack Compose 动画预览?

android - 无法将下载的插件添加到 Cordova/Phonegap 项目

android 在同一个 Activity 中添加两个工具栏?

java - 在这种情况下, java.util.ConcurrentModificationException 是一个大问题吗

单击链接时,Android Webview 滚动到顶部

arrays - 在Kotlin中比较阵列

kotlin - 在 Ktor : Is it supposed to work like this? 中使用 KeyCloak 进行 OAuth

android - MPAndroidChart:从右开始的实时线图

java - 如何在自己的类中模拟 ConcurrentModificationException?

Java 游戏在使用 LinkedList 进行碰撞检测时崩溃