Closed. This question needs debugging details。它当前不接受答案。












想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。

4年前关闭。





当for循环通过Set时,我得到了并发修改异常。 for循环中的代码中没有包含删除,添加或替换的部分,这可能导致此异常。以下是代码片段(我所拥有的代码之一)

Configuration config= new Configuration();
Set<String> events = config.getEvents();
String[] evta=null;
for(String evt: events){
   evta=evt.split(";");
   //... using the evta for creating new strings but not adding, removing or modifying the events Set<String>.

}


因此,我想知道是什么原因导致了此异常。有任何想法吗?

最佳答案

遍历events时,请勿修改它。为了避免ConcurrentModificationException,您需要使用Iterator

    Iterator<String> iter = events.iterator();
    while(iter.hasNext())
    {
        String item = iter.next();
        if(item.equals(<what>)) {
            iter.remove(); //or split() or whatever.
        }
    }


请显示更多行,以确定哪些行特别引起了后备数组的修改,从而抛出ConcurrentModificationException,但是使用Iterator很有可能避免它。

10-08 01:18