使用iterator和iterator.remove()时出现ConcurrentModificationException

dwj*_*ton 3 java collections iterator concurrentmodification

    private int checkLevel(String bigWord, Collection<String> dict, MinMax minMax)
{
    /*value initialised to losing*/
    int value = 0; 
    if (minMax == MinMax.MIN) value = 1; 
    else value = -1; 


    boolean go = true;

    Iterator<String> iter = dict.iterator();

    while(iter.hasNext())
    {
        String str = iter.next(); 
        Collection<Integer> inds = naiveStringSearch(bigWord, str);

        if(inds.isEmpty())
        {
            iter.remove();
        }

        for (Integer i : inds)
        {
            MinMax passin = minMax.MIN;
            if (minMax == MinMax.MIN) passin = minMax.MAX;

            int value2 = checkLevel(removeWord(bigWord, str, i), dict, passin); 
            if (value2 == -1 && minMax == minMax.MIN)
            {
                value = -1; 
                go = false;
            }
            if (value2 == 1 && minMax == minMax.MAX)
            {
                value = 1; 
                go = false; 
            }

        }

        if (go == false) break; 
    }


    return value;
}
Run Code Online (Sandbox Code Playgroud)

错误:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:810)
at java.util.HashMap$KeyIterator.next(HashMap.java:845)
at aStringGame.Main.checkLevel(Main.java:67)
at aStringGame.Main.test(Main.java:117)
at aStringGame.Main.main(Main.java:137)
Run Code Online (Sandbox Code Playgroud)

这有什么问题?

NPE*_*NPE 5

某处某处正在修改dict.我怀疑它可能会在这个电话中发生:

int value2 = checkLevel(removeWord(bigWord, str, i), dict, passin);
                                                     ^^^^
Run Code Online (Sandbox Code Playgroud)

编辑基本上,会发生的是递归调用通过另一个迭代器checkLevel()修改.这使得外部迭代器的快速失败行为成为可能.dict


jah*_*roy 5

在使用迭代器迭代它时,您无法修改集合.

您尝试调用iter.remove()会破坏此规则(也可能是您的removeWord方法).

CAN修改列表而迭代如果您使用的ListIterator迭代.

您可以将Set转换为List并使用List迭代器:

List<String> tempList = new ArrayList<String>(dict);
ListIterator li = tempList.listIterator();
Run Code Online (Sandbox Code Playgroud)

另一种选择是在迭代时跟踪要删除的元素.

例如,您可以将它们放在Set中.

然后,您可以在循环后调用dict.removeAll().

例:

Set<String> removeSet = new HashSet<String>();
for (String s : dict) {
    if (shouldRemove(s)) {
        removeSet.add(s);
    }
}
dict.removeAll(removeSet);
Run Code Online (Sandbox Code Playgroud)