Java Arrays
Java Arrays
What is an Array?
So far, you have been working with variables that hold only one
value. The integer variables you have set up have held only one
number, and the string variables just one long string of text. An
array is a way to hold more than one value at a time. It's like a list of
items. Think of an array as the columns in a spreadsheet. You can
have a spreadsheet with only one column, or lots of columns. The
data held in a single-list array might look like this:
int[ ] aryNums;
The only difference between setting up a normal integer variable
and an array is a pair of square brackets after the data type. The
square brackets are enough to tell Java that you want to set up an
array. The name of the array above is aryNums. Just like normal
variables, you can call them almost anything you like (with the same
exceptions we mentioned earlier).
But this just tells Java that you want to set up an integer array. It
doesn't say how many positions the array should hold. To do that,
you have to set up a new array object:
aryNums[1] = 14;
And to assign a value of 36 to array position 2, it's this:
aryNums[2] = 36;
Don't forget, because arrays start at 0, the third position in an array
has the index number 2.
If you know what values are going to be in the array, you can set
them up like this instead:
int[ ] aryNums = { 1, 2, 3, 4 };
This method of setting up an array uses curly brackets after the
equals sign. In between the curly brackets, you type out the values
that the array will hold. The first value will then be position 0, the
second value position 1, and so on. Note that you still need the
square brackets after int, but not the new keyword, or the repetition
of the data type and square brackets. But this is just for data types
of int values, string, and char values. Otherwise, you need the new
keyword. So you can do this:
System.out.println( aryNums[2] );
The above code will print out whatever value is held at array
position 2 in the array called aryNums. But let's get some coding
practice.
Start a new project and call it anything you like. Don't forget to
change the name of the Class to something relevant.
When you run the programme you should see this in the Output
window:
Change the array position number in the print line from 2 to 5 and
18 should print out instead.
In the next part, we'll take a look at how to use arrays with loops.
Arrays come into their own with loops. You have seen in the
previous section that to assign values to array positions, you did
this:
aryNums[0] = 10;
But that's not terribly practical if you have a lot of numbers to assign
to an array. As an example, imagine a lottery programme that has to
assign the numbers 1 to 49 to positions in an array. Instead of
typing a long list of array positions and values you can use a loop.
Here's some code that does just that:
i < lottery_numbers.length
Length is a property of array objects that you can use to get the size
of the array (how many positions it has). So this loop will keep going
round and round while the value in the variable i is less than the
size of the array.
To assign values to each position in the array, we have this line:
lottery_numbers[i] = i + 1;
Instead of a hard-code value between the square brackets of the
array name, we have the variable called i. This increases by 1 each
time round the loop, remember. Each array position can then be
accessed just by using the loop value. The value that is being
assigned to each position is i + 1. So again, it's just the incremented
loop value, this time with 1 added to it. Because the loop value is
starting at 0, this will give you the numbers 1 to 49.
The other line in the loop just prints out whatever value is in each
array position.
(If you wanted, you could then write code to jumble up the numbers
in the array. Once you have jumbled up the values, you could then
take the first 6 and use them as the lottery numbers. Write another
chunk of code that compares a user's 6 numbers with the winning
numbers and you have a lottery programme!)
Now that you have imported the Arrays library, you can use the sort
method. It's quite easy:
Arrays.sort( aryNums );
First you type the word "Arrays", then a dot. As soon as you type a
dot, NetBeans will display a list of things you can do with arrays.
Type the word "sort". In between a pair of round brackets, you then
put the name of the array you want to sort. (Notice that you don't
need any square brackets after the array name.)
And that's it - that's enough to sort the array! Here's some code to
try out:
The for loop at the end will go round and round printing out the
values in each array position. When the code is run, the Output will
look like this:
As you can see, the array has been sorted in ascending order.
Here's a loop that goes round all the positions in the array, printing
out whatever is at each position:
int i;
for ( i=0; i < aryString.length; i++ ) {
System.out.println( aryString[i] );
}
The loop goes round and round while the value in the variable
called i is less than the length of the array called aryString.
When the above programme is run, the Output window will look like
this:
You can perform a sort on string arrays, just like you can with
integers. But the sort is an alphabetical ascending one, meaning
that "aa" will come first over "ab". However, Java uses Unicode
characters to compare one letter in your string to another. This
means that uppercase letter will come before lowercase ones. Try
the following code:
When the programme is run, the Output window will display the
following:
Although we've sorted the array, the word "This" comes first. If this
were an alphabetical sort, you'd expect the word "a" to come first."
And it does if all the letters are lowercase. In your programming
code, change the capital "T" of "This" to a lowercase "t". Now run
your programme again. The Output window will now display the
following:
As you can see, the word "this" is now at the bottom. We'll have a
closer look at strings in the next section, so don't worry too much
about them now. Instead, try these exercises.
Exercise G
Set up an array to hold the following values, and in this order: 23, 6,
47, 35, 2, 14. Write a programme to get the average of all 6
numbers. (You can use integers for this exercise, which will round
down your answer.)
Answer to Exercise G
Exercise H
Using the above values, have your programme print out the highest
number in the array.
Answer to Exercise H
Exercise I
Using the same array above, have your programme print out only
the odd numbers.
Answer to Exercise I
A multi dimensional array is one that can hold all the values above.
You set them up like this:
aryNumbers[0][0] = 10;
aryNumbers[0][1] = 12;
aryNumbers[0][2] = 43;
aryNumbers[0][3] = 11;
aryNumbers[0][4] = 22;
So the first row is row 0. The columns then go from 0 to 4, which is
5 items. To fill the second row, it would be this:
aryNumbers[1][0] = 20;
aryNumbers[1][1] = 45;
aryNumbers[1][2] = 56;
aryNumbers[1][3] = 1;
aryNumbers[1][4] = 33;
The column numbers are the same, but the row numbers are now
all 1.
aryNumbers[ i ][ j ]
So the two loop system is used to go through all the values in a
multi-dimensional array, row by row.
Exercise J
Finish off the programme above where we are writing a programme
to print out all the values from the spreadsheet. Your Output window
should look something like this when you're done:
Answer to Exercise J
Once you have a new ArrayList objects, you can add elements to it
with the add method:
listTest.get( 3 )
This line will get the item at Index position 3 on the list. Index
numbers start counting at zero, so this will be the fourth item.
You can also remove items from an ArrayList. You can either use
the Index number:
listTest.remove(2);
Or you can use the value on the list:
Iterator it = listTest.iterator( );
This sets up a new Iterator object called it that can be used to go
through the items in the ArrayList called listTest. The reason for
using an Iterator object is because it has methods called next and
hasNext. You can use these in a loop:
When the code is run, the Output window will display the following:
first item
second item
third item
7
Whole list=[first item, third item, 7]
Position 1=third item
To sum up, then, use an ArrayList when you're not sure how many
elements are going to be in a list of items.
We'll leave arrays, for now, and move on. In the next section, we'll
tackle strings.