This question already has answers here:
ConcurrentModificationException for ArrayList [duplicate]
                                
                                    (6个答案)
                                
                        
                                6年前关闭。
            
                    
我正在vaadin框架中工作。我有一个绝对布局,并向该布局添加了一些组件,现在我要迭代绝对布局以从绝对布局中获取所有组件,同时我要从同一绝对布局中删除一个或多个组件。但这给了我并发修改异常。帮助我如何避免异常。要求是在迭代相同布局的同时从绝对布局中删除组件。

生成异常的代码:

Iterator<?> iterate = absoluteLayout.getComponentIterator();
    while (iterate.hasNext())
    {
        Component c = (Component) iterate.next();
        if(c instanceof Button)
        {
            Button button = (Button) c;
            if(button.getCaption().equals(""))
            {
                Long id = (Long) button.getData();
                if(id == subSystemId)
                {
                    flag = true;
                    absoluteLayout.removeComponent(button);
                    absoluteLayout.removeComponent(tempLabel);
                    absoluteLayout.removeComponent(tempOptionGroup);

                    System.out.println("Waooo!! Components has been removed fro absolute layout!!");
                }
            }
        }
        else if(c instanceof Label)
        {
            tempLabel = (Label) c;
        }
        else if(c instanceof OptionGroup)
        {
            tempOptionGroup = (OptionGroup) c;
        }
    }


例外是:

java.util.ConcurrentModificationException
at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(LinkedHashMap.java:394)
at java.util.LinkedHashMap$KeyIterator.next(LinkedHashMap.java:405)
at com.medmax.Dashboard.cchpi.ROSComponent.removeRosSubSystemLogic(ROSComponent.java:401)


.......

最佳答案

您正在同一循环内从absoluteLayout迭代并删除。
而是尝试在tempLabel循环外声明诸如tempOptionGroupbuttonwhile之类的变量。

它应该解决你的问题

07-28 02:13
查看更多