ConcurrentModificationException when using iterator and iterator.remove()

前端 未结 4 1960
旧时难觅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 tempList = new ArrayList(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 removeSet = new HashSet();
    for (String s : dict) {
        if (shouldRemove(s)) {
            removeSet.add(s);
        }
    }
    dict.removeAll(removeSet);
    

提交回复
热议问题