2012-10-03 53 views
0

嗨,我读了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.

任何人都可以请解释吗?

+0

您的意思是否使用'increaseObject(I);'? (注意'I'而不是'i') – lccarrasco

+1

Integer在Java中是不可变的。 相似的主题:http://stackoverflow.com/questions/5560176/java-is-integer-immutable – Alex

+0

@Alexey,那么在这种情况下,考虑到Integer是不可变的,在'increaseObject'方法中发生了什么? – rgamber

回答

1

问题是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); 
+0

Ahh ..我完全忽略了后缀++部分。对不起,这是一个愚蠢的错误。 – rgamber

+0

@rgamber:没问题,它会发生。 :) –

1

increasedObject2()功能,

返回的n ++;

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