我遇到了以下问题:
private void doStuff(int i) {
if(i>10) {
return;
}
doStuff(i++);
}
public void publicMethod() {
doStuff(i);
}
我希望它运行
doStuff
10次然后返回。然而
i++
在 doStuff
之前不会被执行再次被调用 0
.结果是无限循环。我知道如何修复它,但我想知道这种行为是正确的还是错误的。
最佳答案
Now I would expect this to run doStuff 10 times and then return, however i++ does not get execute before the doStuff is called again with 0.
是的,后增量运算符的结果是原始值...然后在下一次调用该方法时,您有一个新的
i
.换句话说,这个调用:doStuff(i++);
相当于:
int original = i;
i = original + 1;
doStuff(original);
来自 JLS section 15.14.2 :
The value of the postfix increment expression is the value of the variable before the new value is stored.
鉴于您不使用
i
之后再次(因此任何副作用都是毫无意义的),为什么不简化你的生活?doStuff(i + 1);
(与 Java 中的所有参数一样,您会看到按值传递 - 在方法中更改
i
的值不会更改调用方参数的值。)
关于作为参数传递时,Java 后增量 (++) 的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12860070/