Most of us know how to initialize arrays. A usual way to initialize array is to specify all its elements. For example an array of integers can be initialized in following way:
Integer[] integerArray = new Integer[] {
new Integer(1),
new Integer(2),
new Integer(4)
};
I was generating code for a unit test and needed to create a List that I would pass to the constructor of a particular class I wanted to test. So I took the easiest way to create array then convert it to the list. In the process I generated the elements of the array by copying and pasting previously added element. The code looked like this:
List initList = Arrays.asList(new Integer[] {
new Integer(1),
new Integer(2),
new Integer(1),
new Integer(2),
});
Notice the trailing comma! To my surprise, my IDE did not warn me about compilation error, moreover the code compiled and ran just fine.
According to Java Language Specification, chapter 10.6 Array Initializers
An array initializer is written as a comma-separated list of expressions, enclosed by braces "{" and "}".
The length of the constructed array will equal the number of expressions.
The expressions in an array initializer are executed from left to right in the textual order they occur in the source code. The nth variable initializer specifies the value of the n-1st array component. Each expression must be assignment-compatible (§5.2) with the array's component type, or a compile-time error results.
If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.
A trailing comma may appear after the last expression in an array initializer and is ignored.
I must admit that I never used trailing commas in arrays in my whole software engineering career and on this occasion, this took my be surprise. I guess making mistakes it one way of discovering the truth and realizing that a mistake may not be a mistake after all.
So, there you go! Initializing arrays in Java with a trailing comma is totally valid. I learn something new every day :-)