[英]Will this ever result in a stack overflow error?
增加对象的实例变量是否会导致堆栈溢出错误?
例如:
此方法(java)将导致堆栈溢出错误:
class StackOverflow {
public static void StackOverflow (int x)
{
System.out.println (x) ;
StackOverflow(x+1) ;
}
public static void main (String[]arg) { StackOverflow (0) ;
}
但这会吗?:(.....是我为缩短代码而插入的间隙。其长度应足够长。)
import java.util.*;
class Dice
{
String name ;
int x ;
int[] sum ;
....
public Dice (String name)
{
this.name = name ;
this.x = 0 ;
this.sum = new int[7] ;
}
....
public static void main (String[] arg)
{
Dice a1 = new Dice ("a1") ;
for (int i = 0; i<6000000; i++)
{
a1.roll () ;
printDice(a1) ;
}
}
....
public void roll ()
{
this.x = randNum(1, this.sum.length) ;
this.sum[x] ++ ;
}
public static int randNum (int a, int b)
{
Random random = new Random() ;
int c = (b-a) ;
int randomNumber = ((random.nextInt(c)) + a) ;
return randomNumber ;
}
public static void printDice (Dice Dice)
{
System.out.println (Dice.name) ;
System.out.println ("value: "+Dice.x) ;
printValues (Dice) ;
}
public static void printValues (Dice Dice)
{
for (int i = 0; i<Dice.sum.length; i++)
System.out.println ("#of "+i+"'s: "+Dice.sum[i]) ;
}
}
上面的当前当前不会导致堆栈溢出错误,但是如果我在main中更改了这一行,我也能得到它吗: for (int i = 0; i<6000000; i++)
所以那里不是600万的足够高的东西?
堆栈溢出? 不,但是可能导致整数溢出,这是完全不同的事情。
堆栈溢出意味着方法调用堆栈上的空间已用尽(可能是由于递归调用失控)。 如果整数溢出超过其最大值,则整数将导致int绕到其最小值。
在Java中,堆栈溢出错误来自过度的递归 。 这是函数直接或间接调用自身的地方。
在您的第一个示例中, StackOverflow
函数直接无限制地调用自身。
在您的Dice示例中,没有函数调用其自身的实例,因此您不太可能遇到堆栈溢出错误。
堆栈溢出错误是由无限递归引起的,即无限次递归。 您的第二个代码示例似乎根本没有使用递归,因此我认为不可能发生堆栈溢出错误。
好了,您可以使用-Xss开关更改java中堆栈的最大大小。 最小的堆栈约为1KB,因此您不需要无限(甚至非常多)的递归来获得所需的堆栈溢出,但是您肯定需要比示例中给出的更多的内容。 我想我的观点是,递归足以引起堆栈溢出,但不是必须的。 使用任意小的调用堆栈,您可以使用任意数量的方法调用将其溢出。
这会导致堆栈溢出错误吗?
简单的说:
由于应用程序的递归太深而导致堆栈溢出时,将引发堆栈溢出。 那意味着你的行StackOverflow(x+1) ;
可能引发堆栈溢出错误取决于堆栈的大小。 除此之外,代码还将开始获取意外的int值。
这将导致您出现Integer溢出,因为int类型从大约。 -2E7至2E7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.