问题
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
回答1:
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.
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/4699577/why-does-comma-not-cause-to-compilation-error