我执行了以下代码
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/