Java 代码片段 - 使用变量 Final - 需要解释
final Integer a = 1;
Integer b = a;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 1
b++;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 2
b = b + 1;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 3
b = 10;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 10
如果有人能解释代码输出,特别是与变量 B 的关系,那就太好了。
final Integer a = 1;
Integer b = a;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 1
b++;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 2
b = b + 1;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 3
b = 10;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 10
It would be great if somebody could explain the code output, expecially with relation to variable B.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,让我们从这里开始:
您已经创建了一个对 Integer 对象的最终引用,该对象是从原始 int 中自动装箱的。
此引用只能分配一次,并且不能再次分配。
在这里,您创建了对同一对象的第二个引用,但该引用不是最终的,因此您可以在闲暇时重新分配它。
这是以下语句的简写:
并且,巧合的是,
最后一个语句:
正在使用自动装箱来简写此语句:
希望这会有所帮助。
Ok, let's start with this:
You've created a final reference to an Integer object, which was autoboxed from a primitive int.
This reference can be assigned exactly once, and never again.
here you've created a second reference to the same object, but this reference is not final, so you can reassign it at your leisure.
This is a shorthand for the following statement:
And, coincidentally, the same for
The last statement:
Is using autoboxing to shorthand this statement:
Hope this helps.
首先,你必须知道这里发生了自动装箱,您可以在此处阅读相关内容。
现在只有
b++
让我觉得不简单。它在功能上与此代码等效:尽管字节码可能略有不同。
First of all, you must know that auto-boxing is happening here, you can read about that here.
Now only the
b++
strikes me as non-straightforward. It is functionally equivalent to this code:Though the bytecode may be slightly different.