为什么逗号(,)不会导致编译错误?
我正在编写一段代码,突然发现“,”不会导致任何编译错误。为什么 ?
我的意思是
public enum A {
B, C, ; // no compilation error
}
但是
int a, b, ; // compilation error
I am writing a code that and suddenly see that "," doesn't cause any compilation error. Why ?
What I mean
public enum A {
B, C, ; // no compilation error
}
but
int a, b, ; // compilation error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http://docs.oracle.com /javase/specs/jls/se8/html/jls-8.html#jls-8.9
Enumbody 具有以下规范:
如您所见,EnumConstantList 后面可以有一个可选的逗号,这只是一个符号方便。
http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9
The Enumbody has the following specification:
As you can see there can be an optional comma after the EnumConstantList, this is just a notational convenience.
该语言是这样设计的,以便可以轻松添加和重新排序元素 - 特别是如果每个元素都单独占一行。
与声明变量相比并不是一个好的比较,但数组以同样的方式允许更多值:
基本上,向源代码中定义的集合添加额外的值比想要添加额外的值更常见将变量添加到声明语句中。
The language was designed this way so that it's easy to add and reorder elements - particularly if each one is on a line on its own.
The comparison with declaring variables isn't a good one, but arrays allow for more values in the same way:
Basically, adding on extra values to a collection defined in source code is rather more common than wanting to add a variable to a declaration statement.
主要优点是它使多行列表更易于编辑,并且减少了差异中的混乱。
更改:
to:
只涉及差异中的一行更改:
当省略尾随逗号时,这会击败更令人困惑的多行差异:
后一个差异使得更难看出仅添加了一行而另一行没有改变内容。
基于雷蒙德的回答:https://stackoverflow.com/a/11597911/5111897
The main advantages are that it makes multi-line lists easier to edit and that it reduces clutter in diffs.
Changing:
to:
involves only a one-line change in the diff:
This beats the more confusing multi-line diff when the trailing comma was omitted:
The latter diff makes it harder to see that only one line was added and that the other line didn't change content.
Based on answer by Raymond : https://stackoverflow.com/a/11597911/5111897