java - 迭代 ArrayList <Integer> 时出现 ConcurrentModificationException

标签 java

我正在尝试迭代 Integer ArrayList 并获取每个元素的值,但在 int value = .... 处出现错误

不知道发生了什么。请指教。

Iterator<Integer> listItr = executeList.iterator(); // iterator for the execute list 
    while (listItr.hasNext()) { // iterate through list and do work!
        int robIndex = listItr.next();
        int timer = fakeRob.exeCountDown(robIndex); // decrement first then return timer
        if (timer == 0) {// check if instr finished execution
            System.out.println("timer expired. fire");
            executeList.remove(executeList.indexOf(robIndex)); // 1. remove instr from exeList
            transitState(robIndex, EX, WB); // 2. transit from EX state to WB state
            int tag = fakeRob.getTag(robIndex); // get producer tag
            regFile.setRdy(tag); // 3a. set register file ready flag for this tag
            fakeRob.wakeUp(tag); // 3b. wake up instructions with this tag
        }
    }

错误:

java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at sim.execute(sim.java:180)
at sim.<init>(sim.java:71)
at sim.main(sim.java:270

谢谢

汉克

最佳答案

如果您将正在执行的操作放入循环中,也许会有所帮助。如果您尝试从列表中删除元素,则需要调用 listItr.remove() 来执行此操作。一般来说,您不应该在循环中调用任何修改列表的函数(即 add()、set() 等)。

以下代码将触发此操作

Iterator<Integer> it = executeList.iterator();
while (it.hasNext()) {
  Integer i = it.next();
  executeList.remove(i);
}

正确的做法是:

Iterator<Integer> it = executeList.iterator();
while (it.hasNext()) {
  Integer i = it.next();
  it.remove();
}

其他线程(如上所述)也可能是问题。请记住,迭代器由所有 java 提供的集合中的列表本身支持。因此,如果在您迭代时另一个线程修改了列表,您就会遇到这种情况。

关于java - 迭代 ArrayList <Integer> 时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10466746/

相关文章:

java - 在android中保存结构化数据

java - 如何表示GAME浏览器游戏的棋盘/ map 数据?

java - InputSampler<K,V>中的<K,V>有哪些类型?

java - 如何在java中停止客户端套接字以监听服务器套接字

java - 从 BufferedImage 到文件 : Return Type issues

java - 在 Java 中将特定方法作为线程运行

java - StringTemplate - 如何遍历列表中的列表?

java - egl_emulation eglsurfaceattrib 未使用流媒体播放器实现

java - 如何使用扫描仪读取文件,然后将其放入二维字符数组中

java - JAXB :Need Namespace Prefix to all the elements