且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java对象分配行为不一致?

更新时间:2023-02-01 21:22:49

行为是一致的.这行:

x += 23;

实际上为x分配了一个不同的Integer对象;它不会修改该语句之前的x表示的值(实际上与对象y相同).在后台,编译器将x拆箱,然后将加法23的结果装箱,就像编写代码一样:

actually assigns a different Integer object to x; it does not modify the value represented by x before that statement (which was, in fact, identical to object y). Behind the scenes, the compiler is unboxing x and then boxing the result of adding 23, as if the code were written:

x = Integer.valueOf(x.intValue() + 23);

如果您检查编译时生成的字节码(在编译后只需运行javap -c TestJava),就可以确切地看到这一点.

You can see exactly this if you examine the bytecode that is generated when you compile (just run javap -c TestJava after compiling).

第二部分发生的事情是这一行:

What's going on in the second piece is that this line:

x[0] += 10;

还将一个新对象分配给x[0].但是,由于xy引用相同的数组,因此这也会将y[0]更改为新对象.

also assigns a new object to x[0]. But since x and y refer to the same array, this also changes y[0] to be the new object.