简体   繁体   中英

StackOverflowError on recursive method call

I encounter the following problem: I want to make a program that converts a list of data (it will be airport information like lat/longditude, ICAO etc...) into a database from which I can not only sort them but then have a method printing out certain a script for an other program that needs the data in a different way.

I managed to create a list that splits the original data (from a .txt) by different airports, so that each element contains one (eg (12921, 'CYAC', 'Cat Lake Airport', 'CA', 51.7272, -91.8244, 0, 0, '') ). When I try to use methods that for example just count the list by calling a recursive method that gives back the value of the next element in the list plus its own, I get a StackOverflowError in the Line with if(next!=null) . Here is the method itself:

public int getLength(){
    if(next!=null){
        return next.getLength()+1;
    }
    else{
        return 1;
    }
}

The number of airports is somewhere at the 42000s, but it (appearently) creates 42000 objects just fine, just doesnt want to go through them.

Any ideas on how to avoid that error? Would an array be smarter? Thanks for your help, best regards!

You get a stackOverflow, because the java stack is not so big. You should use an iterative algorithm, similar to this one:

public int getLength(){
    MyObject cursor = this;
    int length = 0;
    while (cursor != null) {
       length += 1;
       cursor = this.next;
    }
}

Where MyObject is the current class.

You have two possible options.

  1. Replace recursion with simple loop, or even non-iterative formula: getLength() of i-th item in the line is n - i + 1 where n is the list length, assuming first item has index 1;

  2. [Not recommended] increase JVM stack size by adding -Xss100m (or any other size you consider suitable) flag to the command starts JVM;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM