Java:为什么我会收到错误消息“类型不匹配:无法将 int 转换为字节"?
如果您声明 byte 或 short 类型的变量并尝试对它们执行算术运算,则会收到错误类型不匹配:无法将 int 转换为 short"(或相应地类型不匹配:无法将 int 转换为字节").
If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte").
byte a = 23;
byte b = 34;
byte c = a + b;
在这个例子中,编译错误在第三行.
In this example, the compile error is on the third line.
推荐答案
虽然算术运算符被定义为对任何数字类型进行操作,但根据 Java 语言规范(5.6.2 Binary Numeric Promotion),字节和短类型的操作数在交给操作员之前会自动提升为 int.
Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators.
要对 byte 或 short 类型的变量执行算术运算,您必须将表达式括在括号中(其中的运算将作为 int 类型执行),然后将结果转换回所需的类型.
To perform arithmetic operations on variables of type byte or short, you must enclose the expression in parentheses (inside of which operations will be carried out as type int), and then cast the result back to the desired type.
byte a = 23;
byte b = 34;
byte c = (byte) (a + b);
下面是给真正的 Java 大师的后续问题:为什么?byte 和 short 类型是非常好的数字类型.为什么 Java 不允许对这些类型进行直接算术运算?(答案不是精度损失",因为首先没有明显的理由转换为 int.)
Here's a follow-on question to the real Java gurus: why? The types byte and short are perfectly fine numeric types. Why does Java not allow direct arithmetic operations on these types? (The answer is not "loss of precision", as there is no apparent reason to convert to int in the first place.)
更新:jrudolph 建议此行为基于 JVM 中可用的操作,具体而言,仅实现全字和双字运算符.因此,要对字节和短裤进行操作,必须将它们转换为 int.
Update: jrudolph suggests that this behavior is based on the operations available in the JVM, specifically, that only full- and double-word operators are implemented. Hence, to operator on bytes and shorts, they must be converted to int.
相关文章