【问题标题】:How to solve ConcurrentModificationException when using a pair of lists in a recursive function?在递归函数中使用一对列表时如何解决 ConcurrentModificationException?
【发布时间】:2017-04-10 00:59:32
【问题描述】:

所以我试图通过递归设置每个节点的子节点来平衡二叉搜索树:

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() 使用顺序遍历将树的值(名称)和键(键)存储在它们各自的列表中。 Names 是 List&lt;String&gt;,keys 是 List&lt;Integer&gt;

不幸的是,平衡在尝试访问列表的任何行都会引发异常。

这是错误:

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)

第 43 行是int newRootIndex = keyList.size()/2;

谢谢!

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

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

        buildArrays(focusNode.rightChild);
    }
}

【问题讨论】:

  • 您使用的列表实现是什么?
  • 在方法调用中,传入的列表分别是 ArrayList 和 ArrayList 用于键和名称
  • 你能把buildArrays的代码贴出来吗?
  • 我添加了方法

标签: java list recursion concurrency concurrentmodification


【解决方案1】:

问题在于您使用keyList.subList(),您正在向其中添加新元素,这就是ConcurrentModificationException 的原因。

传递实际子列表的副本,而不是子列表,例如new ArrayList&lt;&gt;(keylist.subList(0, 4)).

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 2017-07-08
      • 2021-12-11
      相关资源
      最近更新 更多