如何通过引用正确传递 Integer 类?

新手上路,请多包涵

我希望有人能为我澄清这里发生的事情。我在整数类中挖掘了一下,但是因为整数 覆盖+ 运算符,所以我不知道出了什么问题。我的问题是这一行:

 Integer i = 0;
i = i + 1;  // ← I think that this is somehow creating a new object!

这是我的推理:我知道 java 是按值 传递(或按引用值传递),所以我认为在下面的示例中,整数对象每次都应该递增。

 public class PassByReference {

    public static Integer inc(Integer i) {
        i = i+1;    // I think that this must be **sneakally** creating a new integer...
        System.out.println("Inc: "+i);
        return i;
    }

    public static void main(String[] args) {
        Integer integer = new Integer(0);
        for (int i =0; i<10; i++){
            inc(integer);
            System.out.println("main: "+integer);
        }
    }
}

这是我的预期输出:

公司:1
主要:1
公司:2
主要:2
公司:3
主要:3
公司:4
主要:4
公司:5
主要:5
公司:6
主要:6
...

这是实际输出。

公司:1
主要:0
公司:1
主要:0
公司:1
主要:0
...

为什么会这样?

原文由 sixtyfootersdude 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

有两个问题:

  1. 整数是按值传递的,而不是按引用传递的。更改方法内部的引用不会反映到调用方法中传入的引用中。
  2. 整数是不可变的。没有像 Integer#set(i) 这样的方法。否则你可以使用它。

要让它工作,您需要重新分配 inc() 方法的返回值。

 integer = inc(integer);


要了解更多有关按值传递的信息,请看另一个示例:

 public static void main(String... args) {
    String[] strings = new String[] { "foo", "bar" };
    changeReference(strings);
    System.out.println(Arrays.toString(strings)); // still [foo, bar]
    changeValue(strings);
    System.out.println(Arrays.toString(strings)); // [foo, foo]
}
public static void changeReference(String[] strings) {
    strings = new String[] { "foo", "foo" };
}
public static void changeValue(String[] strings) {
    strings[1] = "foo";
}

原文由 BalusC 发布,翻译遵循 CC BY-SA 3.0 许可协议

整数是不可变的。您可以将 int 包装在您的自定义包装器类中。

 class WrapInt{
    int value;
}

WrapInt theInt = new WrapInt();

inc(theInt);
System.out.println("main: "+theInt.value);

原文由 Markos 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题