【发布时间】:2011-02-08 03:14:04
【问题描述】:
增加对象的实例变量会导致堆栈溢出错误吗?
例如:
这个方法(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 万个足够高的东西?
【问题讨论】:
-
public class StackOverflow { public static void main(String... args) { main(null); } }现在,that 是StackOverflowError;) -
这个问题的意义何在?简单来说:因为应用递归太深,导致堆栈溢出时抛出堆栈溢出。
-
我敢打赌,如果你通过传递一个 JVM 选项来更改“堆栈最小大小”,那么你可以让骰子滚轮来处理更多的迭代。
-
@ring bearer:虽然大多数时候 StackOverflow 是由深度递归引起的,但这绝对不是唯一的原因:如果你有数千种不同的方法堆叠在一起,它也可能导致 StackOverflow .
-
为什么不自己试试看呢?
标签: java recursion stack-overflow