Multidimensional Structures


You need a two-, three-, or more dimensional array or ArrayList.


No problem. Java supports this.


As mentioned back in Section 7.2, Java arrays can hold any reference type. Since an array is a reference type, it follows that you can have arrays of arrays or, in other terminology, multidimensional arrays. Further, since each array has its own length attribute, the columns of a two-dimensional array, for example, do not all have to be the same length (see Figure 7-2).

Multidimensional arrays

Figure 7-2. Multidimensional arrays

Here is code to allocate a couple of two-dimensional arrays, one using a loop and the other using an initializer. Both are selectively printed.

/** Show Two-Dimensional Array of Objects */ public class ArrayTwoDObjects { /** Return list of subscript names (unrealistic; just for demo). */ public static String[][] getArrayInfo( ) { String info[][]; info = new String[10][10]; for (int i=0; i < info.length; i++) { for (int j = 0; j < info[i].length; j++) { info[i][j] = "String[" + i + "," + j + "]"; } } return info; } /** Return list of allowable parameters (Applet method). */ public static String[][] getParameterInfo( ) { String param_info[][] = { {"fontsize", "9-18", "Size of font"}, {"URL", "-", "Where to download"}, }; return param_info; } /** Run both initialization methods and print part of the results */ public static void main(String[] ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.