gpt4 book ai didi

java - 在递归函数中使用一对列表时如何解决 ConcurrentModificationException?

转载 作者:行者123 更新时间:2023-11-30 10:31:13 24 4
gpt4 key购买 nike

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

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() 使用顺序遍历将树的值(名称)和键(键)存储在各自的列表中。名称是 List<String>键是一个 List<Integer> .

不幸的是,balance 在试图访问列表的任何行都会抛出异常。

这里是错误:

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

最佳答案

问题是你使用了keyList.subList() ,您要向其中添加新元素,这是 ConcurrentModificationException 的原因.

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

关于java - 在递归函数中使用一对列表时如何解决 ConcurrentModificationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43313565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com