自动装箱/加宽发生在 Short a=3 中,但不在 Float a=3 中;
我知道以下代码不起作用,
Float a=3
因为它被翻译为 Float a=Integer.valueOf(3)。我们将在左侧有一个 Float 引用,在右侧有一个 Integer 对象,这是不兼容的。但是:
1.
`Short a=3;`
这是可行的,尽管我们再次在左侧有一个 Short 引用,在右侧有一个 Integer 对象。
2.
Float a=(Float) 3
如果我们没有对 3 进行类型转换,它就会被翻译为 Integer.valueOf(3)。现在,它会被翻译为 Float.valueOf(3) 吗?
I understand that the following code won't work
Float a=3
because its translated as Float a=Integer.valueOf(3). We'll have a Float reference on the LHS and an Integer object on the RHS, which is incompatible. But :
1.
`Short a=3;`
This works, though here again, we'll have a Short reference on the LHS and an Integer object on the RHS.
2.
Float a=(Float) 3
If we hadn't typecasted 3, it would have been translated as Integer.valueOf(3). Now, will it be translated as Float.valueOf(3) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的问题是“为什么 Float f = 3; 不能编译,但 Short s = 3; 可以编译?”,那么答案是:
Java 编译器对整数常量做了一些特殊的工作,以使它们适合左侧:它找到最合适的类型并使用它。因此,
被编译为
本质上,当您编写时会发生相同的魔法
但这仅适用于整数,而不适用于浮点值。
If your question is "Why Float f = 3; does not compile, but Short s = 3; does?", then the answer is:
the Java compiler does some special work on integer constants to fit them with the left-hand side: it finds the most suitable type and uses it. So,
is compiled to
Essentially, the same magic happens when you write
But this is done only for Integers, and not for floating-point values.
缩写形式为:
对于 Double 类型:
The short form is:
For Double type:
如果您尝试使用大于其所能容纳的值来初始化变量(无论该值的数字形式如何),编译器都会给您一条错误消息。
请注意上面代码中 char、byte 和 Short 的最大可能十六进制值。如果超过这些,编译器将自动将该值设为 int 并告诉您需要对赋值进行窄化转换。你就会知道你已经越过了界限。
因此,在您的情况下,
Short s = 3
实际上变为Short s = new Short(3)
并且有效。 (自动装箱时不使用 valueOf 方法,这就是为什么现代 IDE 可以选择将这些自动装箱标记为错误,我们可以用 valueOf 方法替换它们,以更好地管理内存)在第二种情况下
Float a=(Float) 3
将变为Float.valueOf(3)
If you try to initialize a variable with a value bigger than it can hold (regardless of the numerical form of the value), the compiler will give you an error message.
Notice in the above code the maximum possible hexadecimal values for char, byte, and short. If you exceed these, the compiler will automatically make the value an int and tell you that you need a narrowing cast for the assignment. You’ll know you’ve stepped over the line.
So in your case
Short s = 3
actually becomesShort s = new Short(3)
and works. (valueOf methods are not used when Autoboxing that is why modern IDEs have options to flag these autoboxing as errors and we can replace them with the valueOf method for better mgmt of memory)In the second case
Float a=(Float) 3
will becomeFloat.valueOf(3)
无法指定短常量和字节常量,因此编译器允许您透明地转换 int 常量。 java中有浮点常量,因此不支持隐式转换。如果你想要一个 float/Float 我建议你使用 float 常量。
There is no way to specify short and byte constants, so the compiler allows you to translate int constants transparently. There are float constants in java so it doesn't support implied translation. If you want a float/Float I suggest you use a float constant.