在 Java 中将整数值分配给 Float 包装器
以下方法有效
float a=3;
,但以下方法无效:
Float a=3;
3 不应该自动提升为 float (因为加宽转换不需要显式转换),然后装箱为 Float 类型吗?
是因为我在 Khalid Mogul 的 Java 书中读到的规则吗?
无法遵循扩大转化 通过任何拳击转换
The following works
float a=3;
but the following doesn't:
Float a=3;
Shouldn't 3 be automatically promoted to float (as widening conversions don't require an explicit cast) and then Boxed to Float type ?
Is it because of a rule I read in Khalid Mogul's Java book ?
Widening conversions can't be followed
by any boxing conversions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Float a=3;
不起作用的原因是编译器将3
包装到它的 Integer 对象中(本质上,编译器这样做:Float a = new Integer(3);
这已经是一个编译器错误)。 Float 对象不是 Integer 对象(即使它们来自同一个Number
对象)。以下作品:
本质上由编译器翻译为:
或如 Joachim Sauer 提到的,
希望这会有所帮助。
The reason why
Float a=3;
won't work is because the compiler wraps the3
into it's Integer object (in essence, the compiler does this:Float a = new Integer(3);
and that's already a compiler error). Float object isn't and Integer object (even though they come from the sameNumber
object).The following works:
which in essence is translated by the compiler as:
or as Joachim Sauer mentioned,
Hope this helps.
基元和包装器之间存在装箱/拆箱转换,并且存在从一个数字基元到另一个数字基元的提升。但 Java 无法进行两次此转换(在您的情况下,从 int 转换为 Float)。
There is a boxing/unboxing conversion betwen the primitive and the wrapper, and there is a promotion from one numeric primitive to another. But Java is not able to make this conversion twice (convert from int to Float, in your case).
浮点数a=3.0f;会起作用的。
Float a= 3.0f; will work.