Java 参考和价值混淆

Java 参考和价值混淆,java,reference,Java,Reference,嗨,我读了关于堆栈溢出的问题,并尝试做了一个例子 我有以下代码: public static void main(String[] args){ int i = 5; Integer I = new Integer(5); increasePrimitive(i); increaseObject(I); System.out.println(i); //Prints 5 - correct System.out.println(I)

嗨,我读了关于堆栈溢出的问题,并尝试做了一个例子

我有以下代码:

public static void main(String[] args){
     int i = 5;
     Integer I = new Integer(5);

     increasePrimitive(i);
     increaseObject(I);

     System.out.println(i); //Prints 5 - correct
     System.out.println(I); //Still prints 5
     System.out.println(increaseObject2(I)); //Still prints 5

}

public static void increasePrimitive(int n){
     n++;
}

public static void increaseObject(Integer n){
     n++;
}

public static int increaseObject2(Integer n){
         return n++; 
}
increaseObject
是否因为引用值在该函数内发生变化而打印5?我说得对吗? 我不明白为什么
递增对象2
打印5而不是6

有人能解释一下吗?

increasedObject2()
函数中

返回n++


这是后缀。因此,在返回n=5之后,它会增加n值,即n=6。

问题是
返回n++其中n返回,然后仅递增。如果您将其更改为
return++n,它将按预期工作
返回n+1

但是您尝试测试的仍然不能使用
Integer
,因为它是不可变的。你应该试试这样的东西-

class MyInteger {
     public int value; //this is just for testing, usually it should be private

     public MyInteger(int value) {
         this.value = value;
     }
}
这是可变的

然后,您可以传递对该类实例的引用,并从调用的方法中对其进行变异(更改该实例中
value
的值)

改变方法-

public static void increaseObject(MyInteger n){
     n.value++;
}
叫它-

MyInteger i = new MyInteger(5);    
increaseObject(i);

您是否打算使用
increaseObject(I)?(注意,
I
而不是
I
)整数在Java中是不可变的。类似的主题:@Alexey,那么考虑到整数是不可变的,在这种情况下,
increaseObject
方法会发生什么呢?您可以这样更改:n=n+1。这是完全相同的问题:啊……对不起,我完全忽略了后缀++部分。对不起,这是一个愚蠢的错误。@rgamber:没问题,这是经常发生的。:)