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

标签 java integer pass-by-reference

我希望有人可以为我澄清这里发生的事情。我在整数类中研究了一会儿,但因为整数 覆盖 + 运算符我无法弄清楚出了什么问题。我的问题在于这一行:

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

这是我的推理: 我知道 java 是按值传递的( or pass by value of 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);
        }
    }
}

这是我的预期输出:

Inc: 1
main: 1
Inc: 2
main: 2
Inc: 3
main: 3
Inc: 4
main: 4
Inc: 5
main: 5
Inc: 6
main: 6
...

这是实际输出。

Inc: 1
main: 0
Inc: 1
main: 0
Inc: 1
main: 0
...

为什么会这样?

最佳答案

有两个问题:

  1. 整数是按值传递,而不是按引用传递。更改方法内的引用不会反射(reflect)到调用方法中传入的引用中。
  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";
}

关于java - 如何通过引用正确传递 Integer 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3330864/

相关文章:

java - 将参数传递给 HashMap 值中的函数

java - 将整数转换为数字数组

mysql - 当我进行 LEFT JOIN 时,我的 SIGNED INT 被转换为 UNSIGNED

objective-c - Objective-C 对象是按值传递还是按引用传递?

c# - 保存对 int 的引用

java - HyperLinkListener 取消并保存文件

java - 在 JOptionPane 中使用 HTML 标签

java - Spring Security 尽管有限制但仍允许访问

java - 测试字符串中的非数字字符 Luhn Test Java

c++ - 通过引用或指针正确传递 vector