我希望有人可以为我澄清这里发生的事情.我在整数类中研究了一会儿,但因为整数 覆盖 +
运算符我无法弄清楚出了什么问题.我的问题在于这一行:
整数 i = 0;我 = 我 + 1;//← 我认为这是在以某种方式创建一个新对象!
这是我的推理:我知道 java 是按值传递的(或按引用值传递),所以我认为在以下示例中,整数对象应每次递增.
公共类 PassByReference {公共静态整数公司(整数 i){我=我+1;//我认为这一定是**偷偷**创建一个新整数...System.out.println("公司:"+i);返回我;}公共静态无效主要(字符串[]参数){整数整数 = 新整数(0);for (int i =0; i<10; i++){公司(整数);System.out.println("main:"+integer);}}}
这是我的预期输出:
<上一页>公司:1主要:1公司:2主要:2公司:3主要:3公司:4主要:4公司:5主要:5公司:6主要:6...这是实际输出.
<上一页>公司:1主要:0公司:1主要:0公司:1主要:0...为什么会这样?
有两个问题:
Integer#set(i)
这样的方法.否则,您可以直接使用它.要让它工作,你需要重新分配 inc()
方法的返回值.
integer = inc(integer);
<小时>
要了解有关按值传递的更多信息,这里有另一个示例:
public static void main(String...args) {字符串[] 字符串 = 新字符串 [] { "foo", "bar" };更改参考(字符串);System.out.println(Arrays.toString(strings));//仍然是 [foo, bar]更改值(字符串);System.out.println(Arrays.toString(strings));//[foo, foo]}公共静态无效changeReference(字符串[]字符串){字符串 = 新字符串 [] { "foo", "foo" };}公共静态无效changeValue(字符串[]字符串){字符串[1] = "foo";}
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!
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);
}
}
}
This is my expected output:
Inc: 1 main: 1 Inc: 2 main: 2 Inc: 3 main: 3 Inc: 4 main: 4 Inc: 5 main: 5 Inc: 6 main: 6 ...
This is the actual output.
Inc: 1 main: 0 Inc: 1 main: 0 Inc: 1 main: 0 ...
Why is it behaving like this?
There are two problems:
Integer#set(i)
. You could otherwise just make use of it.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 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!