gpt4 book ai didi

java - 迭代 ArrayList 时出现 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-02 07:48:58 24 4
gpt4 key购买 nike

我正在尝试迭代 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/

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