Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Multidimensional Structures

Problem

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

Solution

No problem. Java supports this.

Discussion

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[] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata