嗨,我读了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
打印5,因为参考值该函数内部变化?我对吗? 我很困惑为什么increasedObject2
打印5而不是6.
任何人都可以请解释吗?
您的意思是否使用'increaseObject(I);'? (注意'I'而不是'i') – lccarrasco
Integer在Java中是不可变的。 相似的主题:http://stackoverflow.com/questions/5560176/java-is-integer-immutable – Alex
@Alexey,那么在这种情况下,考虑到Integer是不可变的,在'increaseObject'方法中发生了什么? – rgamber