为什么逗号(,)不会导致编译错误?

发布于 2024-10-12 07:33:27 字数 204 浏览 8 评论 0原文

我正在编写一段代码,突然发现“,”不会导致任何编译错误。为什么 ?

我的意思是

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

瀞厅☆埖开 2024-10-19 07:33:27

http://docs.oracle.com /javase/specs/jls/se8/html/jls-8.html#jls-8.9

Enumbody 具有以下规范:

{ [EnumConstantList] [,] [EnumBodyDeclarations] } 

如您所见,EnumConstantList 后面可以有一个可选的逗号,这只是一个符号方便。

http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9

The Enumbody has the following specification:

{ [EnumConstantList] [,] [EnumBodyDeclarations] } 

As you can see there can be an optional comma after the EnumConstantList, this is just a notational convenience.

画骨成沙 2024-10-19 07:33:27

该语言是这样设计的,以便可以轻松添加和重新排序元素 - 特别是如果每​​个元素都单独占一行。

与声明变量相比并不是一个好的比较,但数组以同样的方式允许更多值:

int[] foo = { 1, 2, 3, };

基本上,向源代码中定义的集合添加额外的值比想要添加额外的值更常见将变量添加到声明语句中。

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:

int[] foo = { 1, 2, 3, };

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.

司马昭之心 2024-10-19 07:33:27

主要优点是它使多行列表更易于编辑,并且减少了差异中的混乱。

更改:

public enum Names{
     MANNY,
     MO,
     JACK,
}

to:

public enum Names{
     MANNY,
     MO,
     JACK,
     ROGER,
}

只涉及差异中的一行更改:

  public enum Names{ 
       MANNY,
       MO,
       JACK,
+      ROGER,
  }

当省略尾随逗号时,这会击败更令人困惑的多行差异:

  public enum Names {
       MANNY,
       MO,
-      JACK
+      JACK,
+      ROGER
  }

后一个差异使得更难看出仅添加了一行而另一行没有改变内容。

基于雷蒙德的回答: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:

public enum Names{
     MANNY,
     MO,
     JACK,
}

to:

public enum Names{
     MANNY,
     MO,
     JACK,
     ROGER,
}

involves only a one-line change in the diff:

  public enum Names{ 
       MANNY,
       MO,
       JACK,
+      ROGER,
  }

This beats the more confusing multi-line diff when the trailing comma was omitted:

  public enum Names {
       MANNY,
       MO,
-      JACK
+      JACK,
+      ROGER
  }

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文