我很难理解这段代码返回时会发生什么。在输出10 9 8 7 6 5 4 3 2 1 0之后,为什么在0之后输出1,而不是再次输出0?
public static void a(int b){
if(b<0)
return;
System.out.println(b);
a(b-1);
a(b+1);
}
尽管此特定示例返回了StackOverflowError,但我认为这不是您要寻找的答案。因此,假装没有出现引起错误的代码行,让我来演示正在发生的事情:
public static void a(int b){
if(b<0)
return;
System.out.println(b);
a(b-1);
a(b+1); //assuming this didn't go to infinity
}
该方法的运行与读取的完全相同,但是您创建了子任务。
它检查if语句,然后输出b的值。然后它运行a(b-1),然后运行a(b + 1)。
您得到奇怪的结果,因为then it runs a(b-1)
实际上它本身就是一系列任务。该方法可以完成我之前提到的所有事情,并且它们都会在第一个实例到达a(b + 1)之前发生。
假设您打过电话 a(1);
1 is not less than 0
print 1
a(1-1) //which is zero a(0)
//begin sub-task a(0)
0 is not less than 0
print 0
a(0-1) // which is -1
//begin sub-task a(-1)
-1 is less than 0 so return
a(0+1)
1 is not less than zero
print 1
a(1-1) // which is zero
zero is not less than zero
print zero
a(0-1)
etc. etc.
认为这可能更容易
public static void a(int b){
if(b<0)
return;
System.out.println(b);
a(b-1);
System.out.println(b + " is done");
}
这样做具有以下功能a(1);
:
if(1 < 0) // false
print 1
begin a(1-1) or a(0)
if(0 < 0) // false
print 0
begin a(0-1) or a(-1)
if(-1 < 0) //true so return IE go back to the calling method
print "0 is done"
print "1 is done"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句