首页 / JAVA / 递归java上的堆栈溢出错误
递归java上的堆栈溢出错误
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了递归java上的堆栈溢出错误,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2631字,纯文字阅读大概需要4分钟。
内容图文
![递归java上的堆栈溢出错误](/upload/InfoBanner/zyjiaocheng/757/af142548cb3841ff8f0950153da1645d.jpg)
我需要找到数组中数字之间最长的方式(从大到小).
我试图编写递归函数并得到java.lang.StackOverflowError,但由于缺乏知识,我不明白为什么会发生这种情况.
首先,我初始化数组并用随机数填充它:
public long[] singleMap = new long[20];
for (int i = 0; i < 20; i++) {
singleMap[i] = (short) random.nextInt(30);
}
然后,我试图找到倒数的最长路径(例如{1,4,6,20,19,16,10,6,4,7,6,1 ……})并返回计数等数字.
public int find(long[] route, int start) {
if (route[start] > route[start + 1]) {
find(route, start++);
} else {
return start;
}
return start;
}
所以这是日志:
08-23 13:06:40.399 4627-4627/itea.com.testnotification I/dalvikvm: threadid=1: stack overflow on call to Litea/com/testnotification/MainActivity;.find:ILI
08-23 13:06:40.399 4627-4627/itea.com.testnotification I/dalvikvm: method requires 36+20+12=68 bytes, fp is 0x4189e318 (24 left)
08-23 13:06:40.399 4627-4627/itea.com.testnotification I/dalvikvm: expanding stack end (0x4189e300 to 0x4189e000)
08-23 13:06:40.400 4627-4627/itea.com.testnotification I/dalvikvm: Shrank stack (to 0x4189e300, curFrame is 0x418a3e88)
08-23 13:06:40.400 4627-4627/itea.com.testnotification D/AndroidRuntime: Shutting down VM
08-23 13:06:40.400 4627-4627/itea.com.testnotification W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41a8ed40)
08-23 13:06:40.414 4627-4627/itea.com.testnotification E/AndroidRuntime: FATAL EXCEPTION: main
Process: itea.com.testnotification, PID: 4627
java.lang.StackOverflowError
at itea.com.testnotification.MainActivity.find(MainActivity.java:46)
at itea.com.testnotification.MainActivity.find(MainActivity.java:46)
我感谢任何解释,因为所有相关问题都没有帮助我.如果我的功能有问题,请更正或解释.
编辑
我忘了说,我用它来检查每个“点”的最长路
for (int i = 0; i < singleMap.length - 1; i++) {
int x = find(singleMap, i);
System.out.println("steps = " + x);
}
解决方法:
您需要保留到目前为止的当前最大值,以及当前值.
所以改变如下:
public int find(int[] route, int start, int max, int currentMax) {
if (currentMax > max) {
max = currentMax;
}
if (start == route.length - 1) {
return max;
}
if (route[start] > route[start + 1]) {
return find(route, start + 1, max, currentMax + 1);
}
return find(route, start + 1, max, 1);
}
并用一个开始调用它
find(route, 0, 1, 0);
第二种方法是在没有递归的情况下重写它:
public int find(int[] route) {
int max = 1;
int currentMax = 1;
for (int i = 0; i < route.length - 1; i++) {
if (route[i] > route[i + 1]) {
currentMax++; // If next element is lower increment currentMax
if (currentMax > max) {
max = currentMax; // If currentMax is the new max update max
}
} else {
currentMax = 1; // If next element is not lower restart from 1
}
}
return max;
}
并称之为
find(route);
内容总结
以上是互联网集市为您收集整理的递归java上的堆栈溢出错误全部内容,希望文章能够帮你解决递归java上的堆栈溢出错误所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。