Sunday, February 04, 2007

Trailing Comma in Arrays

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 :-)

12 comments:

maarvan said...

thanks for the tip!

Unknown said...

This is the same behaviour as Javascript, where it is actually useful. If you using some other languages to generate your Javascript arrays dynamically, and lots of people do, you don't need to worry about the omitting the comma after the last element.

Doug Holton said...

Yeah it works the same way in most other languages.

It makes it so your code will still work if you comment out an item in the array or rearrange items in the array.

a1 = {
one,
two,
three
};

//still works:
a1 = {
one,
two,
//three
};

afsina said...

well, could not you do it as:

List/Integer/ = Arrays.asList(1,2,1,2);

much cleaner but requires Java5. (uses autoboxing and varargs. / symobols are smaller-bigger symbols but blog comment swallows them.)

swankjesse said...

My favourite is this, which is totally legal:
String[] s = new String[] { , }

Anonymous said...

Nice post!

... and just a hint - in case that you like to setup a List dynamically, you don't have to use an array at all.
You could also do it like the following example:

List = new ArrayList(){{
add(1);
add(2);
...
}};

Note the 'double braces' - in this case you override the initialisation of this List instance.

Greetings, Mario
---
http://gleichmann.blog.com

Anonymous said...

Hei Marco,

Be careful with your way because this makes an inner class which have a pointer to its parent class and this could lead to some issues if you try to serialize the list or get rid of the parent object itself (it wont be eligible for GC)

rgds
Martin

Anonymous said...

Pretty awesome. I thought that Mozilla's JS engine was just forgiving. Thanks! :)


----
Jay Garcia
http://tdg-i.com

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Allan V said...

Explorer appears to an extra element to the end of the array if you leave a trailing comma, which doesn't work well if you try to use the array.length or loop through all array elements. This appears to apply to version 6, 7, and 8.

Anonymous said...

This is also a good thing for version control (cvs, subversion, etc), where you want to output diff's of two versions. With the trailing comma, you'll get only a one-line changes when adding a new element at the end of an array, instead of a two-line change (if you write them one element per line).

Note that PHP and perl allow this too, but JavaScript *does not* allow this, even though many major browsers can deal with it. At least some versions of Internet Explorer will not be happy, keep this in mind.

Markus Brenner said...

Actually, this goes back to ANSI-C. See Kernighan/Ritchie, "The C Programming Language", 2nd edition, page 218: A list may end with a comma, a nicety for neat formatting.


Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.