java. Lang. stackoverflowerror Why do I get stackoverflow exception here
•
Java
I have a list of parent and child items displayed in a hierarchy I want to switch their extended property Therefore, if you click a parent and its children are displayed, all parent children are collapsed, and vice versa
The stackoverflow trace points to this row
if (childItem.getItemId() == item.getItemId()) {
hideItemAndDescendants(childItem); //causing stack overflow
}
I think a stack overflow occurs when a method keeps calling it indefinitely But in this case, I have a for loop, which only iterates through the item list. The size of the list is only about 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);
}
}
}
}
Solution
You have a recursive call in hideitemandcalendars:
for (int i = 0; i < items.size(); i++) {
Item childItem = items.get(i);
if (childItem.getItemId() == item.getItemId()) {
hideItemAndDescendants(childItem);
}
}
Therefore, if childitem getItemId()== item. Getitemid(), then call hideitemanddescendants (childitem); Again This may result in an infinite loop, resulting in stackoverflowexception
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
