- Creating Arrays
- Using Arrays
- Multidimensional Arrays
- Sorting an Array
- Workshop: Array of Prizes, Indeed
- Summary
- Q&A
- Quiz
- Activities
Multidimensional Arrays
The arrays you have been introduced to thus far in the hour all have one dimension, so you can retrieve an element using a number ranging from 0 to the largest element number in the array. Some types of information require more dimensions to store adequately as arrays. An example would be the (x,y) coordinate system. If you needed to store a list of x and y coordinates that have a point marked on them, you could use a two-dimensional array. 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. Consider the following:
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 there are 2,500 individual array elements that can hold values (50 multiplied by 50). When the array is created, each element is given the default value of false. Three elements are then given the value of 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 x 50 selectedPoint array was equivalent to creating 2,500 individual variables.