[英]Java - ConcurrentModificationException with recursive method and nested iterators
I have an assignment to write a Java program that will read in a context-free grammar and return the FirstSets of all non-terminals. 我分配了一个Java程序,该程序将在无上下文语法中读取并返回所有非终端的FirstSet。 I've taken a recursive approach with my FirstSet() method:
我使用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;
}
However, I keep getting a ConcurrentModificationException error for the lines: 但是,我不断收到以下行的ConcurrentModificationException错误:
String s = it1.next();
ArrayList<String> nestedFS = firstSet(s);
As far as I can tell, I'm not modifying any lists that I am currently iterating through. 据我所知,我没有修改当前正在迭代的任何列表。 Rather, I am iterating through copies.
相反,我正在遍历副本。 I'm not concerned with redundant memory usage or speed, I just need this to work.
我不关心冗余内存的使用或速度,我只需要它即可工作。
Any clue as to what I'm doing wrong here? 关于我在这里做错什么的任何线索吗? Any help is much appreciated.
任何帮助深表感谢。
Create the copy of ArrayList first using CopyOnWriteArrayList which avoids the ConcurrentModificationException. 首先使用CopyOnWriteArrayList创建ArrayList的副本,这避免了ConcurrentModificationException。
ArrayList<String> copy = first; //replace this line with
CopyOnWriteArrayList<String> copy= new CopyOnWriteArrayList<String>(first);
ArrayList is not threadsafe and need to implement the thread safety, instead, we can use CopyOnWriteArrayList which is thread safe. ArrayList不是线程安全的,需要实现线程安全,相反,我们可以使用具有线程安全性的CopyOnWriteArrayList。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.