嗨,我读到this关于堆栈溢出的问题,并尝试做一个例子。
我有以下代码:
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
是吗? print 5 因为引用的值在该函数内部发生了变化?我对吗?
我很困惑为什么 increasedObject2
打印 5 而不是 6。
谁能解释一下吗?
最佳答案
问题是return n++;
,其中n被返回,然后仅递增。如果将其更改为 return++n;
或 return 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);
关于java - 引用和值(value)混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12701499/