我希望有人可以为我澄清这里发生的事情。我在整数类中研究了一会儿,但因为整数 覆盖 +
运算符我无法弄清楚出了什么问题。我的问题在于这一行:
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 ...
为什么会这样?
最佳答案
有两个问题:
- 整数是按值传递,而不是按引用传递。更改方法内的引用不会反射(reflect)到调用方法中传入的引用中。
- 整数是不可变的。没有像
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/