简体   繁体   English

递归方法调用上的StackOverflowError

[英]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. 我遇到以下问题:我想制作一个程序,将数据列表(它将是纬度/经度,ICAO等机场信息)转换为数据库,我不仅可以对数据库进行排序,还可以方法以某种方式为需要数据的其他程序打印某些脚本。

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, '') ). 我设法创建了一个列表,用于按不同的机场分割原始数据(来自.txt),以便每个元素包含一个(例如(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) . 例如,当我尝试使用仅通过调用递归方法来对列表进行计数的方法来递归列表中下一个元素的值及其自身的值时,我在if(next!=null)的行中收到StackOverflowError 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. 机场的数量大约是42000年代,但它(显然)可以创建42000个对象,只是不想通过它们。

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. 您会得到一个stackOverflow,因为Java堆栈不是很大。 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. 其中MyObject是当前类。

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; 用简单的循环甚至非迭代公式替换递归:假设第一个项目的索引为1,则该行中第i个项目的getLength()n - i + 1 ,其中n为列表长度。

  2. [Not recommended] increase JVM stack size by adding -Xss100m (or any other size you consider suitable) flag to the command starts JVM; [不建议]通过在命令启动JVM中添加-Xss100m (或其他您认为合适的大小)标志来增加JVM堆栈大小;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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