在为对象分配int时,Java是否会自动装箱? [英] Does Java autobox when assigning an int to an Object?

查看:276
本文介绍了在为对象分配int时,Java是否会自动装箱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是自动装箱吗?

Object ob = 8;

上面的代码首先将int literal 8包装在Integer中,然后将其引用分配给变量ob ?因为java语言规范在这种情况下什么都没有。

Will the above code first wrap the int literal 8 in an Integer and then assign its reference to variable ob? Because the java language specification has nothing on this case.

推荐答案


上面的代码是否会首先包装int literal 8在一个Integer中然后赋予它对变量ob的引用?

Will the above code first wrap the int literal 8 in an Integer and then assign its reference to variable ob?

是的。 (或者更确切地说,它会将 int 值装入 Integer 对象,然后将该引用分配给变量 ob 。整数值是一个文字的事实在这里是无关紧要的。它可能是一个方法调用返回 int ,例如。)

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.)


因为java语言规范在这种情况下没有任何内容。

Because the java language specification has nothing on this case.

这不是真的。我的意思是,它明确地处理分配给 Object ,但它的工作方式与普通转换相同。

That's not true. I mean, it doesn't explicitly deal with assigning to Object, but it works the same way as normal conversions.

第5.1节。该规范的7 涉及装箱,它将 int 转换为整数 ...然后分配 Integer 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.

这篇关于在为对象分配int时,Java是否会自动装箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆