如何通过引用正确传递Integer类? [英] How can I pass an Integer class correctly by reference?
问题描述
我希望有人可以为我澄清这里发生的事情。我在整数类中挖了一下但因为整数覆盖 +
运算符我无法弄清楚出了什么问题。我的问题在于这一行:
I am hoping that someone can clarify what is happening here for me. I dug around in the integer class for a bit but because integer is overriding the +
operator I could not figure out what was going wrong. My problem is with this line:
Integer i = 0;
i = i + 1; // ← I think that this is somehow creating a new object!
这是我的理由:
我知道java是按值传递的(或传递引用值),所以我认为在下面的示例中,整数对象应该每个都递增时间。
Here is my reasoning: I know that java is pass by value (or pass by value of reference), so I think that in the following example the integer object should be incremented each time.
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
...
为什么它会像这样?
推荐答案
有两个问题:
- 整数是按值传递的,而不是通过引用传递的。更改方法内部的引用将不会反映到调用方法中的传入引用中。
- 整数是不可变的。没有像
整数#set(i)
这样的方法。否则你可以使用它。
- Integer is pass by value, not by reference. Changing the reference inside a method won't be reflected into the passed-in reference in the calling method.
- Integer is immutable. There's no such method like
Integer#set(i)
. You could otherwise just make use of it.
要使它工作,你需要重新分配<$ c的返回值$ c> inc() method。
To get it to work, you need to reassign the return value of the inc()
method.
integer = inc(integer);
要了解更多关于按值传递的信息,这是另一个例子:
To learn a bit more about passing by value, here's another example:
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";
}
这篇关于如何通过引用正确传递Integer类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!