我希望有人能为我澄清这里发生的事情。我在整数类中挖掘了一下,但是因为整数 覆盖 了 +
运算符,所以我不知道出了什么问题。我的问题是这一行:
Integer i = 0;
i = i + 1; // ← I think that this is somehow creating a new object!
这是我的推理:我知道 java 是按值 传递(或按引用值传递),所以我认为在下面的示例中,整数对象每次都应该递增。
public class PassByReference {
public static Integer inc(Integer i) {
i = i+1; // I think that this must be **sneakally** creating a new integer...
System.out.println("Inc: "+i);
return i;
}
public static void main(String[] args) {
Integer integer = new Integer(0);
for (int i =0; i<10; i++){
inc(integer);
System.out.println("main: "+integer);
}
}
}
这是我的预期输出:
公司:1
主要:1
公司:2
主要:2
公司:3
主要:3
公司:4
主要:4
公司:5
主要:5
公司:6
主要:6
...
这是实际输出。
公司:1
主要:0
公司:1
主要:0
公司:1
主要:0
...
为什么会这样?
原文由 sixtyfootersdude 发布,翻译遵循 CC BY-SA 4.0 许可协议
有两个问题:
Integer#set(i)
这样的方法。否则你可以使用它。要让它工作,您需要重新分配
inc()
方法的返回值。要了解更多有关按值传递的信息,请看另一个示例: