Vincent
Vincent

Reputation: 7

java.util.ConcurrentModificationException when copy a tree structure

I want to copy a tree structure(source) to another one(target), but I got java.util.ConcurrentModificationException when I execute the method below:

private void mergeNode(TreeLayoutNode source, TreeLayoutNode target){

    List<TreeLayoutNode> children = source.getChildren();

    if(CollectionUtils.isEmpty(children)){
        return;
    }

    Iterator<TreeLayoutNode> it = children.iterator();
    while(it.hasNext()){
        **TreeLayoutNode child = it.next();**
        TreeLayoutNode copy = new TreeLayoutNode();
        copy.setName(child.getName());
        copy.setCapacity(child.getCapacity());
        copy.setParent(child.getParent());
        copy.setChildren(child.getChildren());
        copy.setProportions(child.getProportions());
        target.addChildNode(copy);
        mergeNode(child, copy);
    }
}

The code started with "**" is where exception occurs.Could any one give any hints?

Upvotes: 0

Views: 153

Answers (1)

18grady
18grady

Reputation: 51

Remove the call to 'copy.setChildren(child.getChildren())'. This results in references to children from the source tree being added to the destination tree, which is not what you want. The recursive method call will handle filling in the children.

Also you need to set the parent of the new node to the correct node in the new tree rather than calling 'copy.setParent(child.getParent())', which sets the parent reference to a node in the old tree. The call should probably be 'copy.setParent(target)'.

Upvotes: 1

Related Questions