Lesson 10 - Multidimensional arrays in Java

Java Basic constructs Multidimensional arrays in Java

In the previous lesson, Strings in Java - Split, we learned how to use the split() method. Today's tutorial is basically a bonus when it comes to Java basic constructs. We'll discuss what we call multidimensional arrays. Essentially, you could skip directly to the object-oriented programming course; however, I highly recommend that you finish this course first, so you could understand the remaining techniques. After all, this is still just the basics.

We've already worked with a one-dimensional array which we can imagine as a row of boxes in computer memory.

Array structure in Java

(An array of eight numbers can be seen in the image)

Although it's not too common, you may sometimes encounter multidimensional arrays. Especially, when it comes to game applications.

Two-dimensional array

A good representation of a 2-dimensional array is a grid because technically, it is one. A practical application for 2-dimensional arrays would be to use them to store the available seats in a cinema. Here's a visual representation of what I'm referring to:

The 2d array structure in Java

(We can see the available seats of the cinema in the picture )

Of course, a cinema would be bigger in real life, but this array is just fine as an example. 0 means the seat is available, 1 stands for one that isn't. Later, we could also add 2 for reserved seats and so on. It would be more appropriate to create our own data type (called enumerable) for these states, but we'll get into that later. For now, we'll work with numbers.

Java actually doesn't offer any special support for multidimensional arrays, however, we can easily declare them as an array of arrays. The cinema declaration could look like this:

int[][] cinema = new int[5][5];

The first number indicates the number of columns, the second is the number of rows, we could treat it the other way around as well, for example, matrices in mathematics have the number of rows come first.

All numeric arrays in Java are automatically initialized with zeros after the declaration, guaranteed. We've just created a table full of zeros.

Filling the data

Let's fill the cinema room with 1s now as you can see in the picture above. Since we'll be lazy as good programmers should be, we'll use for loops to create a row of 1s :) To access an item of the 2D array we have to enter two coordinates.

cinema[2][2] = 1; // center
for (int i = 1; i < 4; i++) // fourth row
{
        cinema[i][3] = 1;
}
for (int i = 0; i < 5; i++) // the last row
{
        cinema[i][4] = 1;
}

The output

We'll print the array using a loop as we did before. We'll need 2 loops for the 2d array, the first one will iterate over columns and the second one over rows). As proper programmers, won't specify the number of rows and columns directly into the loop because it may change in the future.

We need to keep in mind that if we ask for cinema.length, it'll contain the number of columns (the length of the outer array representing columns). To determine the number of rows (the length of an inner array representing a column) we'll ask for cinema[0].length. Notice that there has to be at least 1 column to make it work.

We'll nest the loops in order so the outer loop would iterate over the rows and the inner one over the columns of the current row. After printing a row, we must break a line. Both loops must have a different control variable:

for (int j = 0; j < cinema[0].length; j++)
{
        for (int i = 0; i < cinema.length; i++)
        {
                System.out.print(cinema[i][j]);
        }
        System.out.println();
}

The result:

Console application
00000
00000
00100
01110
11111

N-dimensional arrays

Sometimes, it may be useful to create an array of even more dimensions. We can all at least imagine a 3D array. Adding on the cinema analogy, we'll say ours has multiple floors, or generally more rooms. The visualization could then look like this:

The 3D array structure in Java

We can create the 3D array the same way we created the 2D array:

int[][][] cinemas = new int [5][5][3];

The code above creates the 3D array as you saw in the picture. We can access it through the indexers, square brackets, as before, but now we have to enter 3 coordinates.

cinemas[3][2][1] = 1; // the second-floor cinema, the third row, the fourth seat

If we ask for cinemas[0][0].length, we'll get the number of "floors".

Jagged arrays

We doesn't have to specify the same length for all the columns. This results into "jagged arrays". An advantage to declaring 2D arrays this way is that we can store as large of an array as we want in each row/column. We can spare some memory this way. The declaration would look something like this:

int[][] cinema = new int[5][];

And we can imagine the array as this:

Jagged arrays of arrays in Java

The disadvantage of this approach is that we need to initialize the array ourselves. The first row of five cells exists, but we'd have to insert the individual columns into it ourselves (we'll insert all the columns with 5 items for now):

for (int i = 0; i < cinema.length; i++)
{
        cinema[i] = new int[5];
}

Java also doesn't make it any easier to retrieve the number of rows and columns of these arrays. We have to determine the array size like this:

int cols = cinema.length;
int rows = 0;
if (cols != 0)
        rows = cinema[0].length;

Notice how it's necessary to retrieve the number of columns first. If it is 0, we can't access the first column to determine its length (number of rows in the column).

The values of the array can be accessed using 2 indexers:

cinema[4][2] = 1; // we occupy a seat at the 5th column and the 3rd row

Shortened initialization of multidimensional arrays

I'll also mention that even multidimensional arrays can be initialized with values directly (the code creates and initializes a crowded cinema room as you can see in the picture):

int[][] cinema = {
        { 0, 0, 0, 0, 1 },
        { 0, 0, 0, 1, 1 },
        { 0, 0, 1, 1, 1 },
        { 0, 0, 0, 1, 1 },
        { 0, 0, 0, 0, 1 }
};

(The array in this code is rotated since we define columns which are declared as rows here).

We can use a similar initialization even for jagged arrays (the code below creates the jagged array from the picture):

int[][] jaggedArray = {
        new int[] {15, 2, 8, 5, 3},
        new int[] {3, 3, 7},
        new int[] {9, 1, 16, 13},
        new int[] {},
        new int[] {5}
};

In conclusion, I would like to add that some people who can't use objects properly, use 2D arrays to store multiple sets of data of a single entity. e.g. imagine that we want to store the length, width, and height of five cell phones. Although you may think that a 3D array would be best for the situation, it can be pulled off with an ordinary 1D array (specifically a list of objects of the Phone type). We'll go over all of that in the object-oriented programming course. If you feel like you could still use some more practice, go ahead and give the exercises for this lesson a shot.

In the next lesson, Mathematical functions in Java - The Math library, we'll look at basic math functions and finish the basic constructs course.


 

Download

Downloaded 39x (17.14 kB)
Application includes source codes in language Java

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
Previous article
Strings in Java - Split
Thumbnail
All articles in this section
Java basic constructs
Activities (7)

 

 

Comments

Avatar
Shecy
Member
Avatar
Shecy:7/22/2017 8:24

jagged array isnt sinking yet but am trying to reason it.....

 
Reply 7/22/2017 8:24
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

1 messages from 1 displayed.