gpt4 book ai didi

java - 获取 java.util.ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-01 08:11:35 24 4
gpt4 key购买 nike

我执行了以下代码

Map<String, SyncPrimitive> syncPrimitives = new HashMap<String, SyncPrimitive>();

for (SyncPrimitive primitive : this.getSyncPrimitives()) {
String groupId = primitive.getId();
primitive.onConnect(groupId);
}

然后我收到以下异常

Error while calling watcher 
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)

在 onConnect 方法中,原始对象被修改。我该如何克服这个问题?

最佳答案

您无法在使用 for-each 迭代期间修改集合。如果要修改,请使用 Iterator .

这种异常描述得很清楚in documentation :

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.

查看相关问题:

关于java - 获取 java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16852469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com