【问题标题】:Java - ConcurrentModificationException with recursive method and nested iteratorsJava - 具有递归方法和嵌套迭代器的 ConcurrentModificationException
【发布时间】:2018-03-10 20:22:16
【问题描述】:

我有一个任务是编写一个 Java 程序,该程序将以上下文无关语法读取并返回所有非终结符的 FirstSets。我的 FirstSet() 方法采用了递归方法:

public static ArrayList<String> firstSet(String nonTerminal){
    ArrayList<String> first = new ArrayList<String>();
    //Find initial elements of FirstSet
    for(String[] current : prodRules) {
        if (current[0].equals(nonTerminal)){ //if the production rule is for that non-terminal
            if(current.length > 2) {
                first.add(current[2]);          //first element after "-->" is added to FirstSet
            } else
                first.add("eps");
        }
    }
    //Add the FirstSet of each element in the initial FirstSet
    ArrayList<String> copy = first; //to avoid ConcurrentModificationException
    Iterator<String> it1 = copy.iterator();
    while(it1.hasNext()) { //recursively find each FirstSet of the initial elements
        String s = it1.next();
        System.out.println("FIRST("+s+")={");
        ArrayList<String> nestedFS = firstSet(s);
        Iterator<String> it2 = nestedFS.iterator();
        while(it2.hasNext()) {
            String f = it2.next();
            if(!first.contains(f))
                first.add(f);
            System.out.print(" "+f+" ");
        }
        System.out.print("}");
    }
    return first;
}

但是,我不断收到以下行的 ConcurrentModificationException 错误:

String s = it1.next();

ArrayList<String> nestedFS = firstSet(s);

据我所知,我没有修改当前正在迭代的任何列表。相反,我正在遍历副本。我不关心多余的内存使用或速度,我只需要它来工作。

关于我在这里做错了什么的任何线索?非常感谢任何帮助。

【问题讨论】:

    标签: java eclipse recursion arraylist iterator


    【解决方案1】:

    首先使用 CopyOnWriteArrayList 创建 ArrayList 的副本,以避免 ConcurrentModificationException。

        ArrayList<String> copy = first; //replace this line with 
        CopyOnWriteArrayList<String> copy= new CopyOnWriteArrayList<String>(first);
    

    ArrayList 不是线程安全的,需要实现线程安全,我们可以使用线程安全的 CopyOnWriteArrayList。

    【讨论】:

    • 这就是解决方案!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    相关资源
    最近更新 更多