Dav*_*vid 1 java stack-overflow recursion
增加对象的实例变量是否会导致堆栈溢出错误?
例如:
此方法(java)将导致堆栈溢出错误:
class StackOverflow {
public static void StackOverflow (int x)
{
System.out.println (x) ;
StackOverflow(x+1) ;
}
public static void main (String[]arg) { StackOverflow (0) ;
}
Run Code Online (Sandbox Code Playgroud)
但这会是吗?:( .....是我为缩短代码而设置的差距.它足够长.)
import java.util.*;
class Dice
{
String name ;
int x ;
int[] sum ;
Run Code Online (Sandbox Code Playgroud)
....
public Dice (String name)
{
this.name = name ;
this.x = 0 ;
this.sum = new int[7] ;
}
Run Code Online (Sandbox Code Playgroud)
....
public static void main (String[] arg)
{
Dice a1 = new Dice ("a1") ;
for (int i = 0; i<6000000; i++)
{
a1.roll () ;
printDice(a1) ;
}
}
Run Code Online (Sandbox Code Playgroud)
....
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]) ;
}
}
Run Code Online (Sandbox Code Playgroud)
以上目前不会导致堆栈溢出错误,但是如果我在main中更改了这一行,我也可以得到它:for (int i = 0; i<6000000; i++)那么有没有600万这样的东西呢?
堆栈溢出?不,但它可能导致整数溢出,这是一个非常不同的事情.
堆栈溢出意味着方法调用堆栈上的空间已耗尽(可能是因为失控的递归调用).如果增量超出其最大值,整数溢出将导致int循环到其最低值.