0

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 (e.g.(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!

4
  • Wouldn't a loop be simpler?
    – stark
    May 19, 2014 at 19:29
  • 3
    You're going to hit Java's recursive limit very quickly with your current approach. Why do you need a recursive solution? May 19, 2014 at 19:32
  • I used a recursive one because that is what we learned in school to be best... obviously not for that kind of sizes :) May 19, 2014 at 19:48
  • You'll could make it tail-recursive and use an accumulator.
    – ggovan
    May 19, 2014 at 20:11

2 Answers 2

0

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.

1
  • Ohhhh that is an awsome idea, thanks a lot, will try it out right away! May 19, 2014 at 19:48
0

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.