5

I'm working through the problems on Codingbat.com and bumped into the fact that for the += operator, a += b isn't necessarily exactly equal to a = a + b. This is well known and has been discussed on SO before, but I bumped into something strange happening when using the charAt() method combined with the above syntax that I can't make sense of.

Say I have two variables:

String str    = "The";
String result = "";

I want to add the first letter in "str" two times to "result". One way of doing this is to:

result = result + str.charAt(0) + str.charAt(0);

which results in result = "TT".

However, if I use the += operator, e.g.:

result += str.charAt(0) + str.charAt(0);

I get result = "168". Clearly character addition has taken place (ASCII code for 'T' is 84, 84*2 = 168).

I'm wondering what is actually going on in the first case using the += operator. According to the docs on assignment operators: E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)). So I would expect the latter expression to output "168" just like using the += operator did. But the following outputs "TT" correctly, and not "168":

result = (String)(result + str.charAt(0) + str.charAt(0));

Have I just misunderstood the documentation? I also found an answer on SO that suggests that str1 += str2 is equivalent to:

str1 = new StringBuilder().append(str1).append(str2).toString();

But evaluating the following:

result = new StringBuilder().append(str.charAt(0)).append(str.charAt(0)).toString();

Still results in "TT", not "168".

Sorry for the long post! I'm just curious at what actually is happening when using charAt() in combination with a String and +=, because the two "equivalents" I've found (if I've translated them from two to three terms correctly) does not produce the same result.

4

3 回答 3

7
result = result + str.charAt(0) + str.charAt(0);

result是一个字符串,所以第一个+执行字符串连接,产生另一个字符串。第二个+,按照相同的逻辑,也将执行字符串连接。这给出了期望的结果。

result += str.charAt(0) + str.charAt(0);

右手边,str.charAt(0) + str.charAt(0),首先被评估。现在,您要添加两个字符,其工作方式类似于简单的整数加法,即添加 ASCII 值。int然后,我们将此结果(在本例中为 -- 84)附加到result,这就是您所看到的。

char c = 'T';
System.out.println(c + c);
168

这里的根本区别只是评估事物的顺序。

于 2014-07-24T15:58:31.123 回答
6

正如您在问题E1 op= E2中所述,等同于E1 = (T)((E1) op (E2)). 所以这条线

result += str.charAt(0) + str.charAt(0);

相当于

result = (String) ((result) + (str.charAt(0) + str.charAt(0)));

(注意 char 添加周围的括号,它们很重要)

这将评估为

result = (String) (("") + ('T' + 'T'));
result = (String) (("") + (168));
result = (String) ("168");
result = "168";

而没有括号你会得到

result = (String) ("" + 'T' + 'T');
result = (String) ("T" + 'T');
result = (String) ("TT");
result = "TT";
于 2014-07-24T16:00:36.397 回答
2
str.charAt(0) + str.charAt(0)

+=在分配发生之前作为一个整体进行评估。

charAt返回 a char,在其上定义加法,就像在整数上一样。因此,这与:

result = result + (str.charAt(0) + str.charAt(0));
于 2014-07-24T15:59:29.113 回答