Java 使用迭代器循环时的ConcurrentModificationException

Java 使用迭代器循环时的ConcurrentModificationException,java,Java,我正在使用迭代器,但调用时似乎仍然会出现修改异常 iterator.next() public void渲染(图形g){ 如果(控制台){ int-boxHeight=0; 迭代器迭代器=output.Iterator(); while(iterator.hasNext()){ boxHeight+=((int)writefont.getStringBounds(迭代器.next(),frc.getHeight()); } 如果(箱高>225){ 箱高=225; } 对于(int i=offse

我正在使用迭代器,但调用时似乎仍然会出现修改异常
iterator.next()

public void渲染(图形g){
如果(控制台){
int-boxHeight=0;
迭代器迭代器=output.Iterator();
while(iterator.hasNext()){
boxHeight+=((int)writefont.getStringBounds(迭代器.next(),frc.getHeight());
}
如果(箱高>225){
箱高=225;
}
对于(int i=offset;i
我的假设是,我正在使用
output.get(I)
访问列表,但我不认为有可能在该场景中添加迭代器


基本上我有一个字符串列表,每个字符串都测量了字体高度并添加到一个整数。

您确定修改异常与迭代器有关吗?在这一行有很多事情要做,还有一些其他可能出错的事情,与迭代器无关


我建议将该行代码分成几行,并将iterator.next()的结果赋给一个变量

不是真的。例外情况是与某种形式的收集有关,而列表“output”是类中唯一的一个。哦!我想我可能知道这里发生了什么。对render()的多个并发调用。您可能需要重新考虑此方法的并发性。也许你不需要每次画图都重新计算整个高度?那有点贵。作为setter/adder方法的一部分,您可以在每次向输出列表中添加某个内容时重新计算高度。然后当然将该值保存为实例变量,并在每次渲染时使用它。谢谢,我接受了您的建议,只在值更改时进行计算,然后我还使用CopyOnWriteArrayList而不是ArrayList。双重列表实际上不是问题,因为该对象仅用于存储调试命令的历史记录。该代码不会导致错误(除非存在线程问题)。对于要抛出的给定异常,必须修改正在迭代的集合,但在给定示例中不能发生这种情况(除非存在线程问题);2)增强的for循环在内部使用迭代器和
hasNext
/
next
,因此,手动调用此类迭代器将其关闭将永远无法解决问题。
public void render(Graphics g) {
    if(consoleShown) {

        int boxHeight = 0;

        Iterator<String> iterator = output.iterator();
        while(iterator.hasNext()) {
            boxHeight += ((int)writefont.getStringBounds(iterator.next(), frc).getHeight());
        }

        if(boxHeight > 225) {
            boxHeight = 225;
        }

        for(int i = offset; i < offset + 25; i++) { //Offset being the line from the list being displayed.
            if(i < output.size()) {
                //Inverse the range to reverse the order of the list being displayed.
                //The irriterator adds the new value to the beginning of the list and not the end to avoid exceptions.
                g.drawString(output.get((int)(Utils.inverseRange(i, output.size())) - 1), 10, (i - offset + 1) * (int)writefont.getStringBounds(output.get(i), frc).getHeight());
            }
        }

        g.drawLine(0, boxHeight + 3, game.getWidth(), boxHeight + 3);
        g.drawString(input, 10, boxHeight + 12);
    }
}