Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Sorting an Array 111

The forloop in Lines 5–12 looks at each character in the mflarray. If the
character is not a space, it is displayed. If it is a space, a .character is dis-
played instead.


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) coordi-
nate 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 multi-
plied 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
selectedPointarray was equivalent to creating 2,500 individual variables.


Sorting an Array


When you have grouped a bunch of similar items together into an array,
one thing you can do is rearrange items. The following statements swap
the values of two elements in an integer array called numbers:


FIGURE 9.1
The output of the SpaceRemover
program.
Free download pdf