如何修复 java.util.ConcurrentModificationException

use*_*419 6 java for-loop hashmap

我的代码导致错误,我不知道如何修复它。我尝试输入打印语句,但它甚至无法做到那么远。出现错误

这是确切的错误

java.util.ConcurrentModificationException
java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(HashMap.java:894)
        at java.util.HashMap$KeyIterator.next(HashMap.java:928)
        at ca.on.oicr.pinery.lims.gsle.GsleClient.getOrders(GsleClient.java:720)
Run Code Online (Sandbox Code Playgroud)

第720行是第二个for循环

Kal*_*Kal 3

如果您想在迭代元素时添加或删除列表中的元素,则可以使用ListIterator 。这是假设你orders是一个列表

所以,你的代码看起来像这样——

ListIterator<Order> it = orders.listIterator();

while ( it.hasNext() ) {
      Order ord = it.next();

      if ( ) // some condition
        it.remove(); // This wil remove the element that we just got using the next() method
      if ( ) // some other condition
        it.add(new Order()); // THis inserts the element immediately before the next call to next()
}
Run Code Online (Sandbox Code Playgroud)