Search code examples
javalistrecursionconcurrencyconcurrentmodification

How to solve ConcurrentModificationException when using a pair of lists in a recursive function?


So I am trying to balance a binary search tree by recursively setting the children of each node:

public void balanceTheTree(){
    root = balance(keys, names);
}

public Node balance(List<Integer> keyList, List<String> nameList){
    buildArrays(root);
    if(root == null){
        return null;
    }
    else{
        int newRootIndex = keyList.size()/2;
        Node focusNode = new Node(keyList.get(newRootIndex), nameList.get(newRootIndex));
        focusNode.leftChild = balance(keyList.subList(0, newRootIndex), nameList.subList(0, newRootIndex));
        focusNode.rightChild = balance(keyList.subList(newRootIndex+1, keyList.size()),nameList.subList(newRootIndex+1, nameList.size()));
        return focusNode;
    }

}

buildArrays() uses an in order traversal to store the trees values (names) and keys (keys) in their respective Lists. Names is a List<String> and keys is a List<Integer>.

Unfortunately balance is throwing an exception at any line that attempts to access the lists.

Here is the error:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(Unknown Source)
at java.util.ArrayList$SubList.size(Unknown Source)
at BinaryTree.balance(BinaryTree.java:43)
at BinaryTree.balance(BinaryTree.java:45)
at BinaryTree.balanceTheTree(BinaryTree.java:34)
at tester.main(tester.java:30)

Where line 43 is int newRootIndex = keyList.size()/2;

Thanks!

public void buildArrays(Node focusNode){
    if(focusNode != null){
        buildArrays(focusNode.leftChild);

        names.add(focusNode.name);
        keys.add(focusNode.Key);

        buildArrays(focusNode.rightChild);
    }
}

Solution

  • The problem is that you use keyList.subList(), to which you are adding new elements and that is a reason for ConcurrentModificationException.

    Instead of sublist, pass a copy of the actual sublist, e.g. new ArrayList<>(keylist.subList(0, 4)).