JavaRush/Java Blog/Random EN/Multidimensional arrays

Multidimensional arrays

Published in the Random EN group
members
Multidimensional arrays - 1

What is a one-dimensional Java array?

An array is an ordered set of elements of the same type, primitive or reference. General information about arrays (mostly one-dimensional) can be found in the article “ Arrays in Java ” and in the JavaRush course . In this article we will talk about arrays whose elements are other arrays. Such arrays are called multidimensional. An array whose elements are other arrays, that is, an array of arrays, is called two-dimensional. Not all languages ​​have multidimensional arrays structured this way, but in Java this is the case.

Java Multidimensional Arrays, General Syntax

In general, multidimensional arrays in Java look like this:
Data_type[dimension1][dimension2][]..[dimensionN] array_name = new data_type[size1][size2].[sizeN];
Where Data_typeis the type of elements in the array. Can be primitive or reference (class). The number of pairs of brackets with dimensioninside is the dimension of the array (in our case - N). array_name— array name size1...sizN— number of elements in each dimension of the array. Declaring multidimensional arrays:
int[][] twoDimArray; //two-dimensional array
String[][][] threeDimArray; //three-dimensional array
double[][][][][] fiveDimArray; // five-dimensional array
Perhaps all this looks very abstract, so now let’s move on to the concrete manifestations of multidimensional arrays - two-dimensional and three-dimensional. The fact is that Java developers sometimes use two-dimensional arrays, much less often - three-dimensional ones, and even larger arrays are extremely rare. There is a high probability that you will not encounter them.

Multidimensional arrays in the JavaRush course

In JavaRush, “ordinary” arrays are started at level 7 of the Java Syntax quest , and later on in the course they are encountered more than once. Sometimes throughout the course you come across problems involving two-dimensional arrays (or ones that can be solved with their help). Two-dimensional arrays are also used in the game engine of the special section “ Games on JavaRush ”. If you haven't been there yet, take a look and create a game or two. The terms and conditions come with detailed instructions and will provide excellent training in programming skills. The three-dimensional array can be found in the game Space Invaders . Through it, a set of frames for animation is specified (and each of these frames is a two-dimensional array). If you've already completed the JavaSyntax quest or just feel confident in Java programming, try writing your own version of this classic game.

What is a two-dimensional Java array?

A two-dimensional array in Java is an array of arrays, that is, each cell contains a reference to an array. But it is much easier to present it in the form of a table that has a given number of rows (first dimension) and number of columns (second dimension). A two-dimensional array in which all rows have an equal number of elements is called rectangular.

Declaring, creating and initializing two-dimensional arrays

The procedure for declaring and creating a two-dimensional array is almost the same as in the case of a one-dimensional one:
int[][] twoDimArray = new int[3][4];
This array has 3 rows and 4 columns. The size of a rectangular two-dimensional array (they may not be rectangular, more on that below), that is, the total number of elements can be determined by multiplying the number of rows by the number of columns. It is now initialized (filled) with default values. That is, zeros. Let's fill it with the values ​​we need.
twoDimArray[0][0] = 5;//write the value 5 into the cell at the intersection of the zero row and zero column
twoDimArray[0][1] = 7; //write the value 7 into the cell at the intersection of the zero row and the first column
twoDimArray[0][2]  = 3;
twoDimArray[0][3] = 17;
twoDimArray[1][0] = 7;
twoDimArray[1][1] = 0;
twoDimArray[1][2] = 1;
twoDimArray[1][3] = 12;
twoDimArray[2][0] = 8;
twoDimArray[2][1] = 1;
twoDimArray[2][2] = 2;
twoDimArray[2][3] = 3;
As with one-dimensional arrays, you can perform the initialization procedure faster:
int [][] twoDimArray = {{5,7,3,17}, {7,0,1,12}, {8,1,2,3}};
In both cases, we will get a two-dimensional array with three rows and four columns, filled with integers. Multidimensional arrays - 2

Displaying a two-dimensional array on the screen

The most logical way to do this operation is to first output the zero line element by element, then the second, and so on. The most common way to output a two-dimensional array in Java is to use two nested loops.
int [][] twoDimArray = {{5,7,3,17}, {7,0,1,12}, {8,1,2,3}};//declared an array and filled it with elements
for (int i = 0; i < 3; i++) {  //go through the lines
            for (int j = 0; j < 4; j++) {//go through the columns
                System.out.print(" " + twoDimArray[i][j] + " "); //output element
            }
            System.out.println();// line wrap for the visual preservation of the tabular form
        }

Fast output of a two-dimensional array

The shortest way to display a list of elements of a two-dimensional array on the screen is to use the deepToStringclass method Arrays. Example:
int[][] myArray = {{18,28,18},{28,45,90},{45,3,14}};
System.out.printLn(Arrays.deepToString(myArray));
The result of the program is the following output: [[18, 28, 18], [28, 45, 90], [45, 3, 14]]

“Lengths” of a two-dimensional array

To get the length of a one-dimensional array (that is, the number of elements in it), you can use the variable length. That is, if we define an array int a[] = {1,2,3}, then the operation a.lengthreturns 3. But what if we apply the same procedure to our two-dimensional array?
int [][] twoDimArray = {{5,7,3,17}, {7,0,1,12}, {8,1,2,3}};
System.out.println(twoDimArray.length);
Output: 3 So this operation outputs the number of rows in the array. How to get the number of columns? If we are dealing with rectangular two-dimensional arrays (that is, those in which all lines are the same length), then we can apply the operation twoDimArray[0].lengthor instead of the zero element (essentially the zero line) - any other existing one. We can do this because in Java, a two-dimensional array is an array of arrays, and element zero twoDimArray[0]is an array of length 4. You can check this yourself.

Example of using a two-dimensional array: checkerboard

Two-dimensional arrays can be used to create any finite two-dimensional field, for example in games, and in particular in chess. It's easy to think of a chessboard as a two-dimensional array. You can “attach” graphics to this, but for now, let’s define a chessboard using symbols and output it to the console. Multidimensional arrays - 3The bottom left square of the chessboard is painted black, the next one is white, as is the one above it. So, the color changes every time you move to a cell adjacent to the side. To set the chess coloring not manually, but using an algorithm, you can use a parity check: if the sum of the row and column index is even or zero, then the cell will be white, otherwise it will be black. For this check, we use the remainder operator % in the algorithm. Since we are working not with graphics, but with symbols, we will denote the white cell with the letter W(white), and the black cell with the letter B(black).
//set the chessboard as a two-dimensional array
String [][] chessBoard = new String[8][8];
        for (int i = 0; i< chessBoard.length; i++) {
            for (int j = 0; j < chessBoard[0].length; j++) {
                if ((i + j) % 2 == 0) chessBoard[i][j] = "W";
                else chessBoard[i][j] = "B";
            }
        }
The output of the program is as follows: WBWBWBWBBWBWBWBWWBWBW BWBBWBWBWBWWBWBWBWBBW BWBWBWWBWBWBWBBWBWBWB W Everything is like on a real chessboard, you can check it. Multidimensional arrays - 4Now let's write a method for correctly numbering cells not in array language, but in “chess” language. The bottom left cell on the board is called A1, while in our array it is chessBoard[7][0]. Let us associate each pair of indices of a two-dimensional array with their “chess” equivalent. To do this, we use two lines - " abcdefgh" and " 87654321" (in reverse order - for simplicity, so that the checkerboard 8 corresponds to the zero column).
public static String chessBoardCoord(int a, int b) {
            String letters = "abcdefgh";
            String numbers = "87654321";
            if ((a > 7)|| (b>7)) return null; //if the number is outside the board, return the default value - null
            else return (Character.toString(letters.charAt(a)) + numbers.charAt(b)); /*charAt - a method with which we extract from the string the element under the passed number, here - under the numbers a and b. Character.toString - a method that converts the received character into a string */
        }
Now let's display in each cell not only its color, but also its number, using the methodchessBoardCoord
String [][] chessBoard = new String[8][8];
        for (int i = 0; i < chessBoard.length; i++) {
            for (int j = 0; j < chessBoard[0].length; j++) {
                if ((i + j) % 2 == 0) chessBoard[i][j] = "W" + chessBoardCoord(j,i);
                else chessBoard[i][j] = "B"+ chessBoardCoord(j,i);
            }
        }

            for (int i = 0; i < chessBoard.length; i++) {
                for (int j = 0; j < chessBoard[0].length; j++) {
                    System.out.print(" " + chessBoard[i][j] + " ");
                }
                System.out.println();
            }
Program output: Wa8 Bb8 Wc8 Bd8 We8 Bf8 Wg8 Bh8 Ba7 Wb7 Bc7 Wd7 Be7 Wf7 Bg7 Wh7 Wa6 Bb6 Wc6 Bd6 We6 Bf6 Wg6 Bh6 Ba5 Wb5 Bc5 Wd5 Be5 Wf5 Bg5 Wh5 Wa4 Bb4 Wc4 Bd4 We4 Bf4 Wg4 Bh4 Ba3 Wb3 Bc3 Wd 3 Be3 Wf3 Bg3 Wh3 Wa2 Bb2 Wc2 Bd2 We2 Bf2 Wg2 Bh2 Ba1 Wb1 Bc1 Wd1 Be1 Wf1 Bg1 Wh1 Where We2means the white square numbered e2.

Example of using a two-dimensional array: matrix multiplication

Attention!This example requires basic knowledge of matrices. Here very little will be said about them, and this information is intended for those who have studied, but have somewhat forgotten, matrix arithmetic. However, this knowledge can be gleaned from open sources, in particular from an article on Wikipedia . This is a good example of using two-dimensional arrays, but we can move on without it. So if it seems incomprehensible to you now from a mathematical point of view, and you don’t really want to delve into it, feel free to skip the example. If you've studied basic linear algebra, you may have learned about rectangular arrays as rectangular matrices. Multidimensional arrays - 5Where a11, a12... aNN are some numbers. In the figure, the matrix is ​​not even rectangular, but square (the number of rows is equal to the number of columns, but this is not always the case). In real life, such matrices are rarely encountered, but in programming and computer science they are very common. In particular, they are used in computer graphics and game engines. For example, the rotation of an object on the screen to any angle can be programmed using a rotation matrix. In two-dimensional space, the rotation matrix looks like this: Multidimensional arrays - 6Where theta is the angle through which the object needs to be rotated. Matrices of equal dimensions can be added to each other, and the addition occurs element-by-element (we add elements with the same indices). But the operation of matrix multiplication is less familiar. Thus, matrices can be multiplied and a resulting matrix can be obtained only if the number of columns of the first matrix coincides with the number of rows of the second. The result matrix will have the same number of rows as the first one and the same number of columns as the second one. Multiplication is performed as follows. Let us have a matrix a[l][m]and b[m][n]. As a result of their multiplication, we should obtain a matrix c[l][n]. To obtain an element of c[0][0]a product matrix, you need to a[0][0]multiply the zero element of the zero row of the first matrix by the zero element of the second matrix, then multiply the first element of the first row of the first matrix by the first element of the first column of the second matrix, and so on, after which all the resulting products are added.

a[0][0]*b[0][0] + a[0][1]*b[1][0] + … + a[0][m-1]*b[m-1][0]
To obtain the second element of the first row of the result matrix, we perform the same procedure with the second row

a[1][0]*b[0][0] + a[1][1]*b[0][1] + … + a[0][m-1]*b[m-1][0]
And so on until the end of the line. Then we move on to the next line and repeat the procedure until we run out of lines. That is, we multiply the rows of the first matrix with the columns of the second matrix. Below is the code for matrix multiplication. You can supplement it with a check for compliance with the above-mentioned condition on the number of rows and columns.
//declaring two matrices
int [][] twoDimArray1 = {{1,0,0,0},{0,1,0,0},{0,0,0,0}};
int[][] twoDimArray2 = {{1,2,3},{1,1,1},{0,0,0},{2,1,0}};

//matrix multiplication process
int[][]twoDimArray3 = new int [twoDimArray1.length][twoDimArray2[0].length];
        for (int i=0; i<twoDimArray3[0].length; i++)
            for (int j=0; j<twoDimArray3.length; j++)
                for (int k=0; k<twoDimArray1[0].length; k++)
                              twoDimArray3[i][j] = twoDimArray3[i][j] + twoDimArray1[i][k] * twoDimArray2[k][j];

//output on display
        for (int i = 0; i < twoDimArray3.length; i++) {
            for (int j = 0; j < twoDimArray3[0].length; j++) {
                System.out.print(" " + twoDimArray3[i][j] + " ");
            }
            System.out.println();
        }
The program outputs the following result: 1 2 3 1 1 1 0 0 0

Non-rectangular two-dimensional arrays

Since two-dimensional arrays are arrays of arrays in Java, each of the inner arrays can be of different lengths. When creating an array, we can only specify the number of rows and not the number of columns (that is, in fact, the length of these same rows). Let's look at an example.
//declaring and creating an array, specifying only the number of rows
int [][] twoDimArray = new int[5][];

//initialize the array, filling it with arrays of different lengths
        twoDimArray[0] = new int[]{1, 2, 3, 4, 5};
        twoDimArray[1] = new int[]{1,2,3,4};
        twoDimArray[2] = new int[]{1,2,3};
        twoDimArray[3] = new int[]{1,2};
        twoDimArray[4] = new int[]{1};
//display the resulting non-rectangular two-dimensional array on the screen
        for (int i = 0; i < twoDimArray.length; i++) {
            for (int j = 0; j < twoDimArray[i].length; j++) {
                System.out.print(" " + twoDimArray[i][j] + " ");
            }
            System.out.println();
        }
Program output: 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 Thus, the zeroth line of our array contains the array {1,2,3,4,5}, and the fourth line contains the array {1}.

Three-dimensional arrays in Java

Following common sense and the logic of the Java language, a three-dimensional array can be called an “array of arrays of arrays” or “an array whose each element is a two-dimensional array.” Moreover, these two-dimensional arrays can be different. Example:
// create a three-dimensional array consisting of two two-dimensional arrays
int[][][] threeDimArr = new int[2][][];
//create the first 2D array of a 5x2 3D array
        threeDimArr[0] = new int[5][2];
//create a second 2D array of a 1x1 3D array
        threeDimArr[1] = new int[1][1];
But more often in practice there are three-dimensional arrays in which all three quantities are defined at once, an analogue of rectangular two-dimensional arrays. Multidimensional arrays - 7As we already mentioned, three-dimensional or more arrays are used very rarely. However, you can program something interesting with a 3D array. For example, a multi-storey car park. Each floor can be considered a two-dimensional array, and a parking space can be considered a specific element of a three-dimensional array. An element of such an array can be represented by a type booleanwith the value false if the space is free and true if the space is occupied.
//set a boolean three-dimensional array. This car park has 3 floors, each of which can accommodate 2x5 = 10 cars. By default, all cells are empty (false)
boolean[][][] parkingLot = new boolean[3][2][5];
//two cars arrived and parked on the ground floor in cell [1][0] and [1][3]
        parkingLot[0][1][0] = true;
        parkingLot[0][1][3] = true;

//Output the array to the console
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 2; j++) {
                for (int k = 0; k < 5; k++) {
                    System.out.print("arr[" + i + "][" + j + "][" + k + "] = " + parkingLot[i][j][k] + "\t");

                }
                System.out.println();
            }
        }

Multidimensional arrays in the real work of a Java programmer

In reality, most Java developers don't encounter multidimensional arrays very often. However, there are a number of tasks for which this data structure is very well suited.

  1. For tests and setting matrices as constants to check a particular algorithm.
  2. Sometimes multidimensional arrays are used for neural networks.
  3. Multidimensional arrays are suitable for archivers.
  4. Working with images.

Interesting problems on two-dimensional and three-dimensional arrays

You know enough about multidimensional arrays in Java and, if you feel confident, you can try solving some of the problems below. They are not easy, but interesting. Tic-tac-toe. Set up a 3x3 field, create two players who take turns. Initially, the field is empty, and in each of the empty fields the first player can put a cross, and the second a zero. The winner is the one who first collects three crosses or three zeros arranged in one row, one column or diagonally.

What else to read

Java game for beginners

Langton's Ant . There is a certain field, divided into cells (a two-dimensional array), painted black or white (can be set by a random function). An “ant” randomly materializes in one of the cells, and at each step it can move in one of four directions to the adjacent cell, horizontally or vertically. Ant movement rules:
  • On a black square, the ant must turn 90° to the left, change the color of its cell to white, then step forward to the next square.
  • On a white square, the ant turns 90° to the right and changes the color of its cell to black, then steps forward to the next square.
Write a method that calculates the iteration at step number ngiven the initial position of the ant. The field can be filled randomly with zeros and ones (or denoted by the letters Wand B, as we did in the chessboard example). We also need two more parameters - the horizontal and vertical position of the ant, as well as its direction at this step (north, south, west, east), while by default the ant looks north. You can try to model a Rubik's cube using three-dimensional arrays. A standard Rubik's cube has 6 faces, and each of them is a three-dimensional array of colored squares Color[][][] rubik = new Color[6][3][3]. However, implementing a Rubik's cube is not a trivial task.

Useful materials about arrays

Many articles on JavaRush are devoted to arrays (mainly one-dimensional ones, since they are much more often used in practice). Pay attention to them.
  1. Arrays in Java - about arrays for beginners with examples
  2. Something About Arrays - Good detailed article on arrays
  3. The Arrays class and its use - the article describes some methods of the classArray
  4. Arrays is the first JavaRush lecture dedicated to arrays.
  5. Return a zero-length array, not null - Effective Programming author Joshua Bloch talks about how to better return empty arrays
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet