stack-Overflow error while removing nodes of a tree

484 views Asked by At

I have a tree structure in this format:

Index1
|
 --Key1
 --Value1 
Index2
|
 --Key2
 --Value2

Key and Value objects are children of Index objects and there are no index objects in the tree.

I'm maintaining array lists for Index objects (indexList), Key objects (keyList) and Value objects (valueList).

viewer is an object of TreeViewer.

My aim is to remove Index object and the code responsible for this action is:

String indexName = text.getText();

for(int i =0; i< model.indexList.size(); i++)
{                   
    if(model.indexList.get(i).getName().equals(indexName))
    {
        Index temp = model.indexList.get(i);
        int noOfKeys   =  temp.keyList.size();
        int noOfValues =  temp.valueList.size();

        for(int j=0; j<noOfKeys ; j++ )
        {
            temp.keyList.remove(j);
            temp.valueList.remove(j);
        } 

        model.indexList.remove(i);
        break;
    }
}
viewer.refresh();

When I perform the remove action the node gets removed but with stack-overflow error.

Please let me know where I went wrong.

1

There are 1 answers

3
seahorse On

The error is because you are removing items from a list in a for loop i.e.

for(int j=0; j<noOfKeys ; j++ )
                    {
                        temp.keyList.remove(j);
                        temp.valueList.remove(j);
                    } 

is most probably the source for the error.

Everytime you remove something from a list the relative index values of all items will change. For example temp.keylist.remove(0) would remove zeroth item and the item at index 1 would move to index zero. Now for the next iteration j has already incremented to 1(but instead it should have been zero)

Try commenting above section of code which I have indicated and you should not get the overflow error(This would your first check to zero in on which part of the code causes the issue)

The next step would be to try something like

temp.keyList.clear()
temp.valueList.clear()

instead of the for loop above.