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

时间:2017-04-10 00:59:32

标签: java list recursion concurrency concurrentmodification

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);
    }
}

2 个答案:

答案 0 :(得分:1)

问题是您使用<div class="card"> <label><input type="radio" name="character">Character 1</label> </div> <div class="card"> <label><input type="radio" name="character">Character 2</label> </div> <div class="card"> <label><input type="radio" name="character" checked>Character 3</label> </div> <div class="card"> <label><input type="radio" name="character">Character 4</label> </div> <div class="card"> <label><input type="radio" name="character">Character 5</label> </div> <script src="http://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>,您要添加新元素,这是keyList.subList()的原因。

而不是子列表,传递实际子列表的副本,例如ConcurrentModificationException

答案 1 :(得分:0)

选项1:如果使用list.remove函数,请使用list iterator.renove() 选项2:尝试使用性能成本的CopyOnWriteArrayList 选项3:将列表转换为数组并执行操作