【问题标题】:Modifying a SnapshotStateList throws ConcurrentModificationException修改 SnapshotStateList 会引发 ConcurrentModificationException
【发布时间】:2022-01-24 03:58:04
【问题描述】:

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 的副本来迭代它可以正常工作,但由于我没有更改列表的大小,是否可以原地执行?

【问题讨论】:

  • 不,我已经看过这个问题,它处理了对我来说很好的删除案例。我需要处理set 的情况,而iterator 没有设置方法。

标签: android kotlin concurrentmodification


【解决方案1】:

一些可能的解决方法是使用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()
}

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2013-05-19
    • 2012-02-07
    相关资源
    最近更新 更多