[英]java.lang.StackOverflowError. Why am I getting a Stackoverflow exception here
I have a list of items that are parents and children, displayed in a hierarchy. 我有一个父级和子级项目列表,以层次结构显示。 I want to toggle their
expanded
property. 我想切换他们
expanded
财产。 so if a parent is clicked and the parent's children are showing then all of the parents children will be collapsed and vice versa 因此,如果单击父级并且父级的子级正在显示,则所有父级子级将被折叠,反之亦然
Stackoverflow trace points to this line Stackoverflow跟踪指向此行
if (childItem.getItemId() == item.getItemId()) {
hideItemAndDescendants(childItem); //causing stack overflow
}
I under stand that a stackoverflow occurs when a method keeps calling it self infinitely .but in this case i have a For loop that only loops over the items
list and the list size is only around 10. 我认为当一个方法一直无限地调用它时会发生堆栈溢出。但是在这种情况下,我有一个For循环,只循环遍历
items
列表,列表大小只有10左右。
public boolean toggleNodeCollapseState(long itemId) {
boolean changed = false; // a flag to determine if anything collapsed or expanded
for (int i = 0; i < items.size(); i++) {
Item childItem = items.get(i);
if (childItem.getParentItemId() == itemId) {
changed = true;
childItem.setCollapsed(!childItem.isCollapsed());
if (childItem.isCollapsed()) {
hideItemAndDescendants(childItem);
} else {
showDescendants(childItem);
}
}
}
return changed;
}
public void hideItemAndDescendants(Item item) {
item.hide();
for (int i = 0; i < items.size(); i++) {
Item childItem = items.get(i);
if (childItem.getItemId() == item.getItemId()) {
hideItemAndDescendants(childItem);
}
}
}
public void showDescendants(Item item) {
item.hide();
for (int i = 0; i < items.size(); i++) {
Item childItem = items.get(i);
if (childItem.getItemId() == item.getItemId()) {
childItem.show();
if (!childItem.isCollapsed()) {
showDescendants(childItem);
}
}
}
}
You have a recursive call in your hideItemAndDecendants: 你在hideItemAndDecendants中有一个递归调用:
for (int i = 0; i < items.size(); i++) {
Item childItem = items.get(i);
if (childItem.getItemId() == item.getItemId()) {
hideItemAndDescendants(childItem);
}
}
So if childItem.getItemId() == item.getItemId()
you call hideItemAndDescendants(childItem);
因此,如果
childItem.getItemId() == item.getItemId()
,则调用hideItemAndDescendants(childItem);
again. 再次。 This probably causes an infinite loop causing your stackoverflowexception.
这可能会导致无限循环导致stackoverflowexception。
My guess is that you've got a data relationship which isn't a true tree - eg 我的猜测是你有一个不是真树的数据关系 - 例如
Item1
|
\- Item2
|
\- Item1
At which point it would just recurse down forever. 在这一点上,它将永远减少。 (Or more simply, an item might be its own child.)
(或者更简单地说,一个项目可能是它自己的孩子。)
One way of diagnosing this would be to write some output at the start of hideItemAndDescendants
to print some identifier for "this" - I'm sure you'll see a loop somewhere. 诊断这个的一种方法是在
hideItemAndDescendants
的开头写一些输出来打印“this”的一些标识符 - 我相信你会在某个地方看到一个循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.