IntelliJ IDEA的抱怨這個代碼:IntelliJ IDEA的抱怨 「字符的隱式數值轉換成int」
char c = 'A';
if (c == 'B') return;
的警告是在第二行:
Implicit numeric conversion from char to int
是什麼意思?它期望我做什麼?
IntelliJ IDEA的抱怨這個代碼:IntelliJ IDEA的抱怨 「字符的隱式數值轉換成int」
char c = 'A';
if (c == 'B') return;
的警告是在第二行:
Implicit numeric conversion from char to int
是什麼意思?它期望我做什麼?
使用靜態Character.compare(char x, char y)
方法而不是使用==
可能更安全。
我還沒有在JLS或JavaDoc中找到任何東西,但可能有潛在的Unicode錯誤使用您的方法。您發佈的警告表明您的字符可能會擴展爲可能會導致性能問題的整數,但我真的懷疑這一點。我會繼續尋找,因爲現在我對此感興趣。
對此的解釋隱藏在JLS中。它指出==
是numerical operator。如果您閱讀文本並按照一些鏈接,您可以發現char
轉換爲int
。它從來不說明確,出現這種情況也是,如果兩個操作數都是char
但says
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
* If either operand is of type double, the other is converted to double.
* Otherwise, if either operand is of type float, the other is converted to float.
* Otherwise, if either operand is of type long, the other is converted to long.
* Otherwise, both operands are converted to type int.
我想最後一個隱含意味着char
始終轉換。也在another section它說"If either operand is not an int, it is first widened to type int by numeric promotion."
。
您收到的警告可能會非常嚴格,但似乎是正確的。
所有字符都被編譯器翻譯爲int。你甚至可以這樣做:
char a = 'b';
int one = a - 46;// it's 40 something...
你可以通過將你的角色轉換爲int來擺脫這個警告。
char c = 'A';
if (c == (int)'B') return;
或
可以使用Character
對象,並使用equal
方法來進行比較。
這不完全正確。 char是一個16位未定義整數(整數表示一個數值,不要與'int'混淆),而'int'是一個32位有符號整數。由於[數字提升],可以將'char'與'int'一起用於詞法表達式中(http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6 ),這在運行時發生,而不是編譯時。 –
不會在Eclipse中發生,也許IntelliJ中的錯誤實現?或者在您的IDE中將警告級別設置得非常高? –
有了Idea13,它不會產生任何警告。 – Admit
您應該打開「數字問題/隱式數字轉換」檢查。但是,我不想擺脫警告。我想了解它是什麼,並改進我的代碼 – yegor256