简体   繁体   English

将整数分配给对象时,Java是否自动装箱?

[英]Does Java autobox when assigning an int to an Object?

Is this autoboxing? 这是自动装箱吗?

Object ob = 8;

Will the above code first wrap the int literal 8 in an Integer and then assign its reference to variable ob? 上面的代码是否会先将int文字8包装为Integer,然后将其引用分配给变量ob? Because the java language specification has nothing on this case. 因为Java语言规范在这种情况下没有任何帮助。

Will the above code first wrap the int literal 8 in an Integer and then assign its reference to variable ob? 上面的代码是否会先将int文字8包装为Integer,然后将其引用分配给变量ob?

Yes. 是。 (Or rather, it will box the int value into an Integer object, and then assign the reference to the variable ob . The fact that the integer value is a literal is irrelevant here, really. It could be a method call returning int , for example.) (或者更确切地说,它将int值装箱到Integer对象中,然后将引用分配给变量ob 。实际上,整数值是文字的事实在这里实际上是无关紧要的。这可以是为int返回的方法调用例。)

Because the java language specification has nothing on this case. 因为Java语言规范在这种情况下没有任何帮助。

That's not true. 这不是真的。 I mean, it doesn't explicitly deal with assigning to Object , but it works the same way as normal conversions. 我的意思是,它没有明确处理分配给Object ,但其工作方式与普通转换相同。

Section 5.1.7 of the specification deals with boxing, which would convert int to Integer ... and then assigning an Integer reference to an Object variable is a normal reference conversion. 规范的第5.1.7节涉及装箱,该装箱会将int转换为Integer ...,然后将Integer引用分配给Object变量是正常的引用转换。

This specific case is detailed in the assignment conversions : 分配转换中详细介绍了这种特定情况:

Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable. 当将表达式的值赋给变量时(第15.26节),将发生赋值转换:必须将表达式的类型转换为变量的类型。
Assignment contexts allow the use of one of the following: 分配上下文允许使用以下之一:

  • [...] [...]
  • a boxing conversion optionally followed by a widening reference conversion 装箱转换(可选)后跟加宽参考转换

So in your case: 因此,在您的情况下:

8 (int) === boxing ===> 8 (Integer) ==== reference widening ===> 8 (Object)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM