Q: 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. 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
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.
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);
                }
            }
        }
    }


A: You have a recursive call in your 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); again. This probably causes an infinite loop causing your stackoverflowexception.

A: My guess is that you've got a data relationship which isn't a true tree - e.g.
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.
