Java Recursive function fails

265 Views Asked by At

My function is:

private void addEdges(mxICell mainObject, List<Object> edgesList) {
        if (mainObject.getEdgeCount() > 0) {
            // for (int i = 0; i < mainObject.getEdgeCount(); i++) {
            edgesList.add(mainObject.getEdgeAt(0));
            addEdges(((Line) mainObject.getEdgeAt(0)).getSource(), edgesList);
        }
        // }
        else
            return;
    }

BEGING UPDATE The function calling is here:

for (Object obj : map.values()) {
                if (obj instanceof Port
                        && ((Port) obj).getParent().getStyle().equals("POWER")) {

                    String Feeder = ((Port) obj).getParent().getValue()
                            .toString();

                    List<Object> edgesList = new ArrayList<Object>();

                    Port p = (Port) obj;

                    mxICell mainObject = p;

                    addEdges(mainObject, edgesList);
//staff
}}

END UPDATE it gives me a

 Exception occurred during event dispatching:
java.lang.StackOverflowError
2

There are 2 best solutions below

2
On

This is because once the edge count of your mainObject is greater than zero the function calls itself over and over again, resulting in a stackoverflow exception. You need to define a proper termination condition.

There is most likely a circle in your datastructure.

For example:

mainObject1.getEdgeAt(0).source == mainObject2
mainObject2.getEdgeAt(0).source == mainObject1

Or something like that. Fact is, your recursive call never terminates.

3
On

As you shown that in commented for loop that you are looping through all the getedge in the mainobject same way you have to reduce the edges from the main object too in case of recursive call. You have to reduce the edge which is already processed in the flow so that when you reach next level one edge is gone.

And also you have to make sure that then you are doing getsource for Line object it will some how reach the level where there are no more edges to process so that your termination condition works correctly.