[英]ConcurrentModificationError when traversing a tree recursively
When traversing a tree structure recursively in order to calculate weights and volumes for an entire bill of materials, I run into a ConcurrentModificationException.当递归遍历树结构以计算整个材料清单的重量和体积时,我遇到了 ConcurrentModificationException。 My approach in pseudocode:
我的伪代码方法:
I have tried to use iterators to allow myself to expand that array of nodes but ran into the same problem.我曾尝试使用迭代器来允许自己扩展该节点数组,但遇到了同样的问题。 Slowly running out of ideas here I am grateful for any hint.
在这里慢慢用完想法,我很感激任何提示。
NOTE: please forgive me to paste my problem not stating all the context for better readability.注意:请原谅我粘贴我的问题,而不是说明所有上下文以提高可读性。 Let me know if you need more info.
如果您需要更多信息,请告诉我。
// Initialization
List<Node> allNodes = new ArrayList<>();
allNodes.add(new Node(input, input, 0, false) // (1)
int counter = 0;
// Method call
getAllNodes(allNodes);
// Query parent for child elements
public void getAllNodes(List<Node> nodes){
for (Node node : nodes) {
if (!node.isVisited()) { // (2)
node.setVisited(true);
String parentId = node.getId();
Product product = QueryUtil.getFirstByIdNo(ctx, parentId, Product.class);
if (isComposite(product)) {
Iterable<Product.Row> rows = product.table().getRows(); // (3)
for (Product.Row row : rows) {
allNodes.add(new Node(parentId, row.getProductListElem().getIdno(), ++counter, false));
--counter;
}
++counter;
// Recursive query of all node elements
getAllNodes(allNodes); // (4)
}
}
}
}
//Node Bean with getters, setters, constructor, toString
@Data
class Node {
String parent;
String id;
int level;
boolean visited;
}
You are getting the error because you are trying to modify the list that you are iterating(reading) over.您收到错误是因为您正在尝试修改您正在迭代(阅读)的列表。 And this is not allowed in JAVA.
而这在 JAVA 中是不允许的。 [for more explanation check here]
[更多解释请点击这里]
To avoid this you can either get an iterator for your list and then loop over it, but that does not seem like a very good option for the code you have posted above.为避免这种情况,您可以为您的列表获取一个迭代器,然后对其进行循环,但这对于您上面发布的代码来说似乎不是一个很好的选择。 Thus, I'll recommend using
List<Node> allNodes = new CopyOnWriteArrayList<>();
因此,我建议使用
List<Node> allNodes = new CopyOnWriteArrayList<>();
instead of List<Node> allNodes = new ArrayList<>()
.而不是
List<Node> allNodes = new ArrayList<>()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.