日期:2014-05-20  浏览次数:21034 次

递归的时候内存溢出一般用什么方法解决
void showSurroundNum(){

//this.setBackground(new Color(225,238,210));
if(surround == -1){
this.setText("pop");
}else if(surround == 0){
for(Mine m:neighborMines){
m.showSurroundNum();//在这里递归的
}
}else {
this.setText((new Integer(surround)).toString());
}
}


运行的时候内存溢出了,用什么方法可以解决?
------解决方案--------------------
递归终止条件,一般有多种方式:
1.  添加递归深度参数到递归函数的参数中
    每次调用深度加一,在函数体中添加条件语句,当深度超过某个值时强行return;
2.  引入元素栈结构,每次递归的一些需要记录的内容,通常会压入栈中,适当的时候再弹出
    在函数体中,添加条件语句,判断栈大小或者栈元素,达到条件时进行return;
------解决方案--------------------
引用:
void showSurroundNum(){

//this.setBackground(new Color(225,238,210));
if(surround == -1){
this.setText("pop");
}else if(surround == 0){
for(Mine m:neighborMines){
m.showSurroundNum();//在这里递归的
}
}else {
this.setText((new Integer(surround)).toString());
}
}


运行的时候内存溢出了,用什么方法可以解决?


我没猜错的话你这个方法就是写在Mine这个类里面的吧?我不知道你是怎么设计的,为什么要在Mine类里面的集合还装Mine类型的数据。或许你应该这样写
void showSurroundNum(){
for(Mine m:neighborMines){
//this.setBackground(new Color(225,238,210));
if(surround == -1){
this.setText("pop");
}else if(surround == 0){

m.showSurroundNum();//在这里递归的

}else {
this.setText((new Integer(surround)).toString());
}
}
}