小编典典

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

java

我希望有人可以为我澄清这里发生的事情。我在整数类中挖了一下,但是由于整数 覆盖+运算符,所以我无法弄清楚出了什么问题。我的问题是这条线:

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

这是我的推理:我知道java通过值传递(或通过reference的值传递),因此我认为在下面的示例中,整数对象应每次递增。

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
...

为什么会这样?


阅读 264

收藏
2020-09-08

共1个答案

小编典典

有两个问题:

  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";
}
2020-09-08