在Java中,给定以下内容:
String a = "str";
CharSequence b = "charseq";你可以写
b = b + a;但不能写入(给出一个编译器错误)
b += a;错误是
incompatible types
found : java.lang.CharSequence
required: java.lang.String现在,在JLS中,这可以通过15.26.2 Compound Assignment Operators中的这一行来解释
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中的错误?
发布于 2011-09-07 14:34:46
编译器错误是您的javac版本中的一个错误。作为pointed in prior answer,此错误已在Java7中修复。
参见例如Sun bug数据库中的Bug ID 7058838:
以下函数不能在java 1.6或更低版本中编译。但它可以用java1.7编译。
公共静态空main(String[] args) { Object x= "x";String y= "y";x += i;}
Not a Defect
有关背景信息,另请参阅旧Bug Id 4741726
o += s形式的表达式,其中o是Object类型的变量,s是String类型的表达式。我们最近修复了这个问题(4642850),这导致了构建失败(4741702)。也许这很常见,我们应该放宽规范,而不是修复编译器??java:compiler
Java7(B25)-据我所知,这意味着在 7
2002-09-04
JLS3允许使用Object+=String,因为'+‘表示字符串连接,能够将对象与字符串连接起来就像字符串与对象连接一样简单。
2008-01-31
发布于 2011-09-07 04:20:52
那应该是个javac bug。
在javac 7中编译得很好。所以有人报告了这个问题,并且已经修复了。
发布于 2011-09-06 21:24:09
从本质上讲,你回答了自己的问题:
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类型
https://stackoverflow.com/questions/7320546
复制相似问题