Multidimensional Arrays

The arrays thus far in the hour all have one dimension, so you can retrieve an element using a single number. Some types of information require more dimensions to store adequately as arrays, such as points in an (x,y) coordinate system. One dimension of the array could store the x coordinate, and the other dimension could store the y coordinate.

To create an array that has two dimensions, you must use an additional set of square brackets when creating and using the array, as in these statements:

boolean[][] selectedPoint = new boolean[50][50];
selectedPoint[4][13] = true;
selectedPoint[7][6] = true;
selectedPoint[11][22] = true;

This example creates an array of Boolean values called selectedPoint. The array has 50 elements in its first dimension and 50 elements in its second dimension, so 2,500 individual array elements can hold values (50 multiplied by 50). When the array is created, each element is given the default value of false. Three elements are given the value true: a point at the (x,y) position of 4,13, one at 7,6, and one at 11,22.

Arrays can have as many dimensions as you need, but keep in mind that they take up a lot of memory if they’re extremely large. Creating the 50 by 50 selectedPoint array was equivalent to creating 2,500 individual variables.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.167.183