java JLS与Sun javac的对应关系/它们不匹配的原因
在Java中:
String a = "str";
CharSequence b = "charseq";
你可以写
b = b + a;
但无法写入(给出编译器错误)
b += a;
错误是
incompatible types
found : java.lang.CharSequence
required: java.lang.String
在第二版中,{a1}现在可以解释:
All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.
但在JLS第三版中,这个评论消失了,关于复合运算符的唯一说法是在15.26.2 Compound Assignment Operators:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
这似乎不起作用(见上文)
所以我的问题是——javac和JLS之间的关系到底是什么?这个特定的例子是javac中的错误还是JLS中的错误
# 1 楼答案
本质上,你回答了自己的问题:
All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.
请注意,左边的操作数不是String类型
# 2 楼答案
编译器错误是您的javac版本中的一个错误。正如pointed in prior answer这个错误在Java7中已经修复
参见Sun bug数据库中的egBug ID 7058838:
描述:
不是缺陷
有关背景信息,请参见old Bug Id 4741726
java:编译器
7(b25)——据我所知,这意味着Java 7的构建25中已修复
# 3 楼答案
那应该是一个javac错误
在JavaC7中编译得很好。所以有人报告了它,它被修复了