【问题标题】:Reference and Value confusion [duplicate]参考和价值混淆[重复]
【发布时间】:2012-10-03 03:31:15
【问题描述】:

您好,我阅读了有关堆栈溢出的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。

谁能解释一下?

【问题讨论】:

标签: java reference


【解决方案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);

【讨论】:

  • 啊..对不起,我完全忽略了后缀 ++ 部分。抱歉,这是一个愚蠢的错误。
  • @rgamber:没问题,它发生了。 :)
【解决方案2】:

increasedObject2()函数中,

返回 n++;

是后缀。所以返回 n = 5 后,增加 n 值,即 n=6。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2021-11-09
    • 1970-01-01
    • 2012-05-29
    • 2022-01-16
    • 2015-02-06
    • 2014-08-23
    相关资源
    最近更新 更多