IntelliJ IDEA抱怨“将char隐式数字转换为int”

时间:2013-10-22 13:01:49

标签: java intellij-idea

IntelliJ IDEA抱怨此代码:

char c = 'A';
if (c == 'B') return;

警告在第二行:

Implicit numeric conversion from char to int

这是什么意思?它对我的期望是什么?

3 个答案:

答案 0 :(得分:2)

对此的解释隐藏在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."

你得到的警告可能非常严格,但似乎是正确的。

答案 1 :(得分:0)

使用静态Character.compare(char x, char y)方法而不是使用==可能更安全。

我在JLS或JavaDoc中没有找到任何内容,但使用您的方法可能存在潜在的unicode错误。您发布的警告表明您的字符可能会扩大到可能会产生性能问题的整数,但我真的对此表示怀疑。我会继续搜索,因为现在我对此很感兴趣。

答案 2 :(得分:0)

所有字符都由compilator翻译为int。你甚至可以这样做:

char a = 'b';  
int one = a - 46;// it's 40 something...  

您可以通过将角色转换为int来消除此警告。

char c = 'A';
if (c == (int)'B') return;

您可以使用Character对象并使用equal方法进行比较。

相关问题