我希望有人可以为我澄清这里发生的事情.我在整数类中挖了一下但因为整数覆盖了+运算符我无法弄清楚出了什么问题.我的问题在于这一行:
Integer i = 0;
i = i + 1; // ? I think that this is somehow creating a new object!
Run Code Online (Sandbox Code Playgroud)
这是我的推理:我知道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);
} …Run Code Online (Sandbox Code Playgroud)