The topic of arrays and multidimensional arrays has been a
confusing one for me for many years. When I was studying C++, this was a topic
that I always told myself that I would come back to later and try to understand
more about it. Now, I am going to explain to you the concept of arrays and
multidimensional arrays in such a simple way, that you should understand from
just this tutorial.
It might be a good thing to mention that whenever you don’t
understand something, just bulldoze through it until you understand. Read blog
posts, watch videos, discuss it with others and yourself. In the end, you will
learn that some things are so simple, only that they are explained in a way
that is no simple for you. You have to find a way to make it simple for you.
What is an Array?
If we type int number = 19; we are telling Java to create
enough space to hold an integer value, which from a past tutorial we saw is 32
bits. So this is what we are telling Java: “Create enough space to hold a
32-bit integer labeled number and assign the value of 19 to it.”
Now, this is how we write an array in Java: int[] numbers;
Let me point out that difference between int number = 19; and
int[] numbers; is that the former actually holds the value 19, but the latter
points to a list of integers. The array does not hold values. While the former
is akin to creating a bucket that can hold values, the latter is akin to
creating a label. In other words, we are creating a list of values that will be
referred to by one name.
How to Initialize an Array
When we create an array, we can give values to it like this:
int[] numbers = {1, 8, 65, 1562, 784521};
String[] names = {“Brian”, “Veronicah”, “Michael”};
double[] prices = {35.50, 20.99, 45.99, 47.20};
If you look at the above examples, you will see what I’m
trying to explain: An array is just a list of values that we reference using a
single label.
It is easier for me to write String[] names = {“Brian”,
“Veronicah”, “Michael”}; than to do the following:
String name1 = “Brian”;
String name2 = “Veronicah”;
String name3 = “Michael”;
Rather than creating all the above variables separately, I
can create an array of type String with the label names, and then access them
through that name.
How to Access Values in an Array
The values in an array can be accessed by writing the label
of the array, followed by the index or location of the value you want to access
enclosed in square brackets. So let’s say we have the array names:
String[] names = {“Brian”, “Veronicah”, “Michael”};
If I want to access the name Brian, I will write: names[0];
If I want to access the name Veronicah, I will write:
names[1];
If I want to access the name Michael, I will write: names[2];
When referencing arrays, the first value in the array usually
has an index of zero (0).
Now, let’s say we have an array of doubles:
double[] prices = {35.50, 20.99, 45.99, 47.20};
How would we access the value 45.99? Well, we now that the
first value in an array has an index of zero. So 35.50 has an index 0, 20.99
has an index 1, 45.99 has an index 2 and 47.20 has an index 3. So the value
45.99 can be accessed by writing the prices[2];
Another Way to Initialize Arrays
Okay now we know one way of initializing arrays, which is,
for example:
double[] prices = {35.50, 20.99, 45.99, 47.20};
In the above example, we create the array and initialize it
in one statement.
Now, there is another way to do this that you should know.
First, you can declare your array like this without giving it
any initial values:
String[] animals;
Now this array contains no values. We normally say that this
array is uninitialized. Since we haven’t added values to the array, Java
doesn’t know whether it will refer to 1, 5, 1000 or even 2 values. So if you
know the number of values that your array will refer to, you can write it
within the square brackets like this:
String[3] animals;
This tells Java that your array will contain three String
values that will be referenced by the label “animals.”
So later on, we can initialize the above array by referring to
the indexes like this:
To initialize the first value, we can write: animals[0] =
“cat”;
To initialize the second value, we can write: animals[1] =
“mongoose”;
To initialize the third value, we can write: animals[2] =
“horse”;
This means that you can either choose to initialize your
arrays in one line like this:
String[] animals = {“cat”, “mongoose”, “horse”};
String[3] animals = {“cat”, “mongoose”, “horse”};
Or, you can first declare it and then initialize it later
like this:
String[3] animals;
animals[0] = “cat”;
animals[1] = “mongoose”;
animals[2] = “horse”;
Notice that when you are initializing your arrays in one
line, there is no need to place the number of values in the square brackets
like this:
String[3] animals = {“cat”, “mongoose”, “horse”};
It will still work even without the number 3 in the square
brackets because you’ve already told Java the values that will be in your
array.
Multidimensional Arrays
Multidimensional arrays are very simple. I admit they took me
years to understand, but I persevered until I found someone who explained it to
me in a way that cleared all the confusion.
What is a multidimensional array? It is just an array of
arrays.
The word “multi” in “multidimensional” tells you that there
are several dimensions. So there could be two, three, fifty or even more. In
this tutorial, I will talk about two-dimensional and three-dimensional arrays,
because these are what you will encounter or use most of the time.
Initializing Multidimensional Arrays
Let’s say we want to create a two-dimensional array to hold
the names of animals in a farm. You can either use method 1 or 2:
Method 1
String[][] animalsInFarm = {{“llama”, “cow”, “puppy”},
{“goat”, “bull”, “donkey”},
{“rabbit”, “pig”, “bees”}};
I’ve used different lines because I want to make it easy for
you to read. I could have just as well done it in one line like this:
String[][] animalsInFarm = {{“llama”, “cow”, “puppy},
{“goat”, “bull”, “donkey”},
{“rabbit”, “pig”, “bees”}};
Method 2
You can first declare your array and then initialize it later
like this:
String[3][3] animals;
animals[0][0] = “llama”;
animals[0][1] = “cow”;
animals[0][2] = “puppy”;
animals[1][0] = “goat”;
animals[1][1] = “bull”;
animals[1][2] = “donkey”;
animals[2][0] = “rabbit”;
animals[2][1] = “pig”;
animals[2][2] = “bees”;
Now I am guessing you are confused, and that is good, because
what I’m about to tell you will clear your confusion. You should think as
multidimensional arrays as tables. A table usually has rows and columns. In
your two-dimensional array, the first index i.e. animals[0][0] refers to the row number. The second
index i.e. animals[0][0]
refers to the column number.
So when we say animals[0][0], we are referring to
the value in the first row and the first column. Remember I told you that in
arrays, we always start counting from zero.
Do you now have an idea of what we are saying? Let me draw a
table to show you: We declared String array of animals like this: String
animals[3][3].
Because we always start counting from zero, it means that there
are three rows and three columns. We always start with the row and then the
column. So we can draw a three by three table for the array:
|
Column 0
|
Column 1
|
Column 2
|
Row 0
|
“llama”
|
“cow”
|
“puppy”
|
Row 1
|
“goat”
|
“bull”
|
“donkey”
|
Row 2
|
“rabbit”
|
“pig”
|
“bees”
|
Table 1: An illustration on how to visualize 2 dimensional
arrays.
So from Table 1, if we want to reference “bull”, we say that
it is in row 1 because we start counting from zero and column 1 i.e.
animals[1][1];
If we want to reference “bees”, we say that it is in row 2
because we start counting from zero and column 2 i.e. animals[2][2];
Three-Dimensional Arrays
Three-dimensional arrays have three indices. For example,
going back to our animals example, we can declare a three-dimensional array
like this:
String[3][3][2] animals;
The first index i.e. String[2][2][1] animals; refers to the number of rows.
In this case, the [2] shows that we have three rows because we always start
counting from zero.
The second index i.e. String [2][2][1] animals; refers to the number of columns.
In this case, the [2] shows that we have three columns because we always start
counting from zero.
The third index i.e. String [2][2][1] animals; refers to the number of groups
of the two dimensional array that exist. In this case, the [1] shows that we
have two groups because we always start counting from zero.
|
Column 0
|
Column 1
|
Column 2
|
Row 0
|
“llama”
|
“cow”
|
“puppy”
|
Row 1
|
“goat”
|
“bull”
|
“donkey”
|
Row 2
|
“rabbit”
|
“pig”
|
“bees”
|
|
Column 0
|
Column 1
|
Column 2
|
Row 0
|
“chicken”
|
“geese”
|
“ducks”
|
Row 1
|
“turkeys”
|
“mule”
|
“pony”
|
Row 2
|
“reindeer”
|
“alligator”
|
“foal”
|
So, let’s say we want to access the animal “foal”. We can see
that it is in the second table in row number 2 and column number 2. So we start
with the row, then the column and finally the group. So “foal” is in
animals[2][2][1].
Now, let’s say we want to access the animal “bees”. We can
see that it is in the first table in row number 2 and column number 2. So we
start with the row, then the column and finally the group. So “bees” is in
animals[2][2][0].
Figure 1: An example of how to initialize a three-dimensional
array and accessing its values.
Note that whenever you try to access a value in an array that
is outside the bounds, Java will give you an error. It throws something called
an Exception “ArrayIndexOutOfBounds”.
So, there you have it on arrays. Try creating arrays of
different types and dimensions. Try initializing the arrays using the methods
I’ve shown you in this tutorial and try accessing them using their indices.
If you have any question or comment, please drop them in the
comments section below and I will answer them as soon as possible. In the next
tutorial, we discuss flow control in Java.
No comments:
Post a Comment