Java Notes

Arrays - More

Anonymous arrays

Anonymous arrays allow you to create a new array of values anywhere in the program, not just in the initialization part of a declaration.

// This anonymous array style can also be used in other statements.
String[] days = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};
You can also use anonymous array syntax in other parts of the program. For example,
// Outside a declaration you can make this assignment.
x = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

Inefficiency. Be careful not to create these anonymous arrays in a loop or as local variables because each use of new will create another array.

Dynamic allocation

Because arrays are allocated dynamically, the initialization values may arbitrary expressions. For example, this call creates two new arrays to pass as parameters to drawPolygon.

g.drawPolygon(new int[] {n, n+45, 188}, new int[] {y/2, y*2, y}, 3);

Converting between arrays and Collections data structures


C-style array declarations

Java also allows you to write the square brackets after the variable name, instead of after the type. This is how array declarations are written in C, but is not a good style for Java. C declaration syntax can get very ugly with part of the declaration before the variable, and part after. Java has a much nicer style where all type information can be written together. There are times when only the Java notation is possible to use.

   int[] a;   // Java style -- good
   int a[];   // C style -- legal, but not Java style

Additional topics