我希望有人能为我澄清这里发生了什么。我在整数类中查找了一段时间,但由于integer类正在覆盖+运算符,所以我无法弄清楚出了什么问题。我的问题出在这一行:
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);
}
}
}
这是我期望的输出结果:
Inc: 1 main: 1 Inc: 2 main: 2 Inc: 3 main: 3 Inc: 4 main: 4 Inc: 5 main: 5 Inc: 6 main: 6 ...
这是实际输出结果:
Inc: 1 main: 0 Inc: 1 main: 0 Inc: 1 main: 0 ...
为什么会出现这种情况?