ConcurrentModificationException when using iterator and iterator.remove()

前端 未结 4 1938
旧时难觅i
旧时难觅i 2021-01-13 16:30
    private int checkLevel(String bigWord, Collection dict, MinMax minMax)
{
    /*value initialised to losing*/
    int value = 0; 
    if (minMax ==          


        
相关标签:
4条回答
  • 2021-01-13 16:38

    You can't modify a Collection while you're iterating over it with an Iterator.

    Your attempt to call iter.remove() breaks this rule (your removeWord method might, too).

    You CAN modify a List while iterating IF you use a ListIterator to iterate.

    You can convert your Set to a List and use a List iterator:

    List<String> tempList = new ArrayList<String>(dict);
    ListIterator li = tempList.listIterator();
    

    Another option is to keep track of the elements you want to remove while iterating.

    You could place them in a Set, for example.

    You could then call dict.removeAll() after your loop.

    Example:

    Set<String> removeSet = new HashSet<String>();
    for (String s : dict) {
        if (shouldRemove(s)) {
            removeSet.add(s);
        }
    }
    dict.removeAll(removeSet);
    
    0 讨论(0)
  • 2021-01-13 16:40

    This is a common occurance in all Collections classes. For instance the entry in TreeSet uses failfast method.

    The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

    http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html

    0 讨论(0)
  • 2021-01-13 16:46

    Something somewhere is modifying dict. I suspect it might be happening inside this call:

    int value2 = checkLevel(removeWord(bigWord, str, i), dict, passin);
                                                         ^^^^
    

    edit Basically, what happens is that the recursive call to checkLevel() modifies dict through another iterator. This makes the outer iterator's fail-fast behaviour to kick in.

    0 讨论(0)
  • 2021-01-13 16:46

    When using a for each loop you are not allowed to modify the Collection you are iterating inside the loop. If you need to modify it, use a classic for loop

    0 讨论(0)
提交回复
热议问题