Java TOPIC 08
– MULTIDIMENSIONAL ARRAYS LESSON NOTE JAVA CODE One
can create a multidimensional array in the same way as one creates a normal
array with one simple exception. You
simply need to include square brackets for each dimension that you want. Inside each bracket, you must also include
the size of the dimension. EXAMPLES Example 1 – Create a two
dimensional integer array that is 2 by 3 in size. int[][] x = new int[2][3]; Example 2 – Create a four dimension String array that is 3 by 5 by 2 by 4 in
size. String[][][][] sa
= new String[3][5][2][4]; NUMBER OF ELEMENTS To
calculate the number of elements in a multidimensional array, we simply
multiply all of the sizes of all the dimensions together. Examples The
number of elements in the array x above is 6 because 2 x 3 = 6. The
number of elements in the array sa above is 120
because 3 x 5 x 2 x 4 = 120. INDEXES For
each dimension, the index work like before.
They range from 0 to its size-1. EXAMPLES – ASSIGNING
VALUES Example 1 – Here is the code that is creating a
2 by 4 2D array and giving values to each element. int[][] arr = new int[2][4]; arr[1][0] = 1; arr[1][1] = 8; arr[1][2] = 2; arr[1][3] = 5; Example 2 – The following assignments statement
would cause errors. arr[0][4] = 2; //the
“4” is out of bounds arr[2][3] = 5; //the
“2” is out of bounds USING LOOPS TO ASSIGN
VALUES We can use
loops to assign the values of elements.
This works in the same way as the it did with one-dimensional arrays. Example – Create a 2D array of size 25 by 42
and initialize each value to a random number. double[][] arr = new double[25][42]; for (int i=0; i < arr.length; i++) //arr.length
is 25 { for (int k=0; k
< arr[i].length; k++) //arr.length[i] is 42
{
arr[i][k] = Math.random();
} } OUTPUTTING FUNCTION IN
ARRAYS We can output
multidimensional arrays to screen by using loops in a very similar way as we
used loops to set the value of each element (see above). However, the
Arrays class once again has a useful function that returns a String
representation of a multidimensional array. String s = Arrays.deepToString(arrayName); Of course,
like before, we do need the import statement at the top of our class: import java.util.Arrays; VISUAL REPRESENTATION We often
pretend that a 2D array is like a simple grid. For example,
the statement Would be a
grid like this: However,
while thinking of 2D arrays like this is probably is fine for most
applications, it is not what actually happens in memory. MULTIDIMENSIONAL ARRAYS
IN MEMORY Multidimensional
arrays are arrays of arrays. So they
are really a bunch of 1-dimensional arrays that are grouped together. For example,
the board[][] array from above would look like this
in memory: |