这是正确的写法:
if ( fieldNames.charAt(4) == 'f' )
在你的原始版本中,"f"
is a String
and fieldNames.charAt(4)
is a char
,并且你不能比较String
with a char
using ==
。如果你写'f'
代替"f"
(如上所述)您将比较char
with a char
.
注意"g" == "h"
也被编译器接受,因为两者"g"
and "h"
are String
对象。但是,您不应该这样做。你应该使用"g".equals("h")
反而。要了解原因,请阅读如何在 Java 中比较字符串? https://stackoverflow.com/questions/513832/。 (简短的版本是someString == otherString
比较会often给出意想不到的答案!)
相比之下'g' == 'h'
既被编译器接受又是正确的代码。
更多背景:JavaString
文字是用双引号引起来的,但是char
文字用单引号括起来;例如
String s = "g";
char c = 'g';
A char
value consists of one and only one character1 but String
value can contain more than one character ... or zero characters.
String s2 = "gg"; valid
char c2 = 'gg'; not valid
String s3 = ""; valid
char c3 = ''; not valid
1 - Actually, calling them characters is technically a stretch. A char
... or a value returned by String.getChar
is actually an unsigned 16 bit number. But Java natively uses Unicode, and 16 bits is not enough to represent all Unicode code points. It was when Java was designed, but then Unicode added more code planes.