Search code examples
javagraphhashmapstack-overflow

Java stack overflow error - Graph algorithm


I am using as a data structure for represent a graph,a HashMap - HashMap (one for the locality and one inside the locality in order to represent the destinations) , i had inserted 20 000 localities. Now i need to make a function to know if exist a path between two Localities, this function is recursive and it require me to make a lot of get objects of my hashMap to work with them. For each destination to make i have always to execute the method get in my api, to give me a copy of the hashMap with the destinations Everytime that i run my program, i get a Stackoverflow error. Why this always happen ? it's due the high recursive calls? Or it 's due the constantly call get method to have a copy of the hashMap of the locality's destinations?

thanks.


Solution

  • Stack overflows are caused by the recursion depth exceeding some fixed limit. This probably has nothing to do with copying the HashMap; that would cause an OutOfMemoryError. If you are doing a graph search recursively, the error is likely caused by either

    1. A depth-first search going too deep, or
    2. A bug in your recursion logic.

    Without more data I can't say which it is. Do note, though, that DFS can be written iteratively using an explicit stack to store the nodes to explore. Posting more code would help us make a better diagnosis.

    Hope this helps!