我下面的遞歸函數在'continue'語句中拋出一個ConcurrentModificationException異常。我查看了ConcurrentModificationException中的一些帖子,並且所有問題似乎都是從元素中移除一個元素,但是我沒有刪除我的函數中的任何元素。java.util.ConcurrentModificationException但是我不刪除
我的函數如下所示:
public static void getRootedTreeHelper(Node n, boolean[] marked, String spacing){
System.out.println(spacing + "in helper with " + n.getId());
marked[n.getId()] = true;
if(n.children.isEmpty())
return;
else{
for(Node child : n.children){
if(marked[child.getId()])
continue; // ConcurrentModificationException is thrown here.
else{
n.addChild(child);
spacing = spacing + "\t";
getRootedTreeHelper(child, marked, spacing);
}
}
}
}
按照要求:節點類的相關部分顯示如下
public class Node {
private int id;
ArrayList<Node> children;
public Node(int id) {
this.id = id;
children = new ArrayList<Node>();
}
/**
* add node n to this node's children
* @param n
*/
public void addChild(Node n) {
children.add(n);
}
// getters and setters()
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
有沒有人有什麼想法?
編輯解決: 我沒有用每個循環遍歷所有的孩子,而是使用for循環。
顯示您的節點類 – Venkatesh 2014-11-20 21:06:51
n.children是什麼類型?你可以添加堆棧跟蹤? – flob 2014-11-20 21:08:41
迭代時添加到列表時,也會發生同樣的'ConcurrentModificationException'。 – 2014-11-20 21:08:47