My below recursive function throws a ConcurrentModificationException on the 'continue' statement. I looked at a few posts on ConcurrentModificationException and all of the problems seem to be with removing an element from an element, but I am not removing any element in my function.
My function is below :
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);
}
}
}
}
As requested : The relevant portions of Node Class are shown below
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;
}
}
Does anyone have any ideas?
Edit solved : Rather than using a for each loop to iterate through all the children, I use a for loop.
From ConcurrentModificationException
Javadoc:
Note that this exception does not always indicate that an object has been concurrently modified by a different thread. (...) For
example, if a thread modifies a collection directly while it is
iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
The bug is adding a child into the collection while also iterating over it.
The fault is only detected by the iterator, when it is incremented in the for
loop.