問題描述
如果您聲明 byte 或 short 類型的變量并嘗試對它們執(zhí)行算術(shù)運(yùn)算,則會(huì)收到錯(cuò)誤類型不匹配:無法將 int 轉(zhuǎn)換為 short"(或相應(yīng)地類型不匹配:無法將 int 轉(zhuǎn)換為字節(jié)").
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;
在這個(gè)例子中,編譯錯(cuò)誤在第三行.
In this example, the compile error is on the third line.
推薦答案
雖然算術(shù)運(yùn)算符被定義為對任何數(shù)字類型進(jìn)行操作,但根據(jù) Java 語言規(guī)范(5.6.2 Binary Numeric Promotion),字節(jié)和短類型的操作數(shù)在交給操作員之前會(huì)自動(dòng)提升為 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 類型的變量執(zhí)行算術(shù)運(yùn)算,您必須將表達(dá)式括在括號(hào)中(其中的運(yùn)算將作為 int 類型執(zhí)行),然后將結(jié)果轉(zhuǎn)換回所需的類型.
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 大師的后續(xù)問題:為什么?byte 和 short 類型是非常好的數(shù)字類型.為什么 Java 不允許對這些類型進(jìn)行直接算術(shù)運(yùn)算?(答案不是精度損失",因?yàn)槭紫葲]有明顯的理由轉(zhuǎn)換為 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 中可用的操作,具體而言,僅實(shí)現(xiàn)全字和雙字運(yùn)算符.因此,要對字節(jié)和短褲進(jìn)行操作,必須將它們轉(zhuǎn)換為 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.
這篇關(guān)于Java:為什么我會(huì)收到錯(cuò)誤消息“類型不匹配:無法將 int 轉(zhuǎn)換為字節(jié)"?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!