Hour 9. Storing Information With Arrays
Hour 9. Storing Information With Arrays
No one benefited more from the development of the computer than Santa Claus. For centuries,
humankind has put an immense burden on him to gather and process information. Old St. Nick has to
keep track of the following things:
Naughty children
Nice children
Gift requests
Women who want more from Santa than Mrs. Claus is willing to let him give
Countries that shoot unidentified aircraft first and ask questions later
Computers were a great boon at the North Pole. They are ideal for the storage, categorization, and
study of information.
The most basic way that information is stored in a computer program is by putting it into a variable.
However, this method is limited to relatively simple usage. If Santa had to give each naughty child his
or her own variable name, he'd be working on the program for the next 12 holiday seasons at least, to
say nothing of the effect on his jolly disposition.
The list of naughty children is an example of a collection of similar information. Each child's name is
a string of text or some kind of Santa Information System ID number. To keep track of a list of this
kind, you can use arrays.
Arrays are groups of related variables that share the same type. You can have arrays of any type of
information that can be stored as a variable. Arrays can be used to keep track of more sophisticated
types of information than a single variable, but they are almost as easy to create and manipulate as
variables.
Creating an array
Sorting an array
Creating Arrays
Arrays are variables that are grouped together under a common name. The term array should
be familiar to you, though the meaning might not be so clear—think of a salesman showing
off his array of fabulous cleaning products, or a game show with a dazzling array of prizes.
Like variables, arrays are created by stating the type of the variable being organized into the
array and the name of the array. The difference lies in the addition of the square bracket
marks [ and ].
You can create arrays for any type of information that can be stored as a variable. For
example, the following statement creates an array of string variables:
String[] naughtyChild;
Here are two more examples:
int[] reindeerWeight;
boolean[] hostileAirTravelNations;
Note
Java is flexible about where the square brackets are placed when an array is being created.
You can put them after the variable name, instead of after the variable type, as in the
following:
String niceChild[];
To make arrays easier for humans to spot in your programs, you should probably stick to one
style rather than switching back and forth, though Java allows both styles of usage.
The previous examples create arrays, but they do not store any values in them initially. To do
this, you must either use the new statement along with the variable type or store values in the
array within { and } marks. You also must specify how many different items will be stored in
the array. Each item in an array is called an element. The following statement creates an array
and sets aside space for the values that it will hold:
int[] elfSeniority = new int[250];
This example creates an array of integers called elfSeniority. The array has 250 elements in it
that can be used to store the months that each of Santa's elves has been employed at the Pole.
If the rumors are true and Santa runs a union shop, this information is extremely important to
keep track of.
When you create an array with the new statement, you must specify the number of elements.
Each element of the array is given an initial value when it is set up with new; the value
depends on the type of the array. All numeric arrays have the value 0, char arrays have the
value '\0', and boolean arrays have the value false. A String array and all other objects are
created with the initial value of null.
For arrays that are not extremely large, you can set up their initial values at the same time that
you create them. The following example creates an array of strings and gives them initial
values:
String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",
"Comet", "Cupid", "Donder", "Blitzen" };
The information that should be put into elements of the array is placed between { and }
brackets, with commas separating each element. The number of elements in the array is not
specified in the statement because it is set to the number of elements in the comma-separated
list. Each element of the array in the list must be of the same type. The preceding example
uses a string for each of the reindeer names.
Once the array is created, you cannot make more space and add another variable to the array.
Even if you recall the most famous reindeer of all, you couldn't add "Rudolph" as the ninth
element of the reindeerNames array. A Java compiler won't let poor Rudolph join in any
reindeerNames.
Using Arrays
You use arrays in a program as you would use any variable, except for the element number in
between the square brackets next to the array's name. Once you refer to the element number,
you can use an array element anywhere a variable could be used. The following statements all
use arrays that have already been defined in this hour's examples:
elfSeniority[193] += 1;
niceChild[94287612] = "Max";
if (hostileAirTravelNations[currentNation] == true)
sendGiftByMail();
An important thing to note about arrays is that the first element of an array is numbered 0
instead of 1. This means that the highest number is one less than you might expect. For
example, consider the following statement:
String[] topGifts = new String[10];
This statement creates an array of string variables that are numbered from 0 to 9. If you
referred to topGifts[10] somewhere else in the program, you would get an error message like
the following when you run the program:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
at Gift.main(Gift.java:4);
Like all of the error messages encountered in Java, this one's a bit hard to decipher. The key
thing to note is the part that mentions an exception, because exceptions are another word for
errors in Java programs. This exception is an "array out of bounds" error, which means that a
program tried to use an array element that doesn't exist within its defined boundaries.
If you want to check the upper limit of an array during a program so you can avoid going
beyond that limit, you can use a variable called length that is associated with each array that is
created. The length variable is an integer that contains the number of elements an array can
hold. The following example creates an array and then reports its length:
String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",
"Comet", "Cupid", "Donder", "Blitzen", "Rudolph" };
System.out.println("There are " + reindeerNames.length + " reindeer.");
In this example, the value of reindeerNames.length is 9, which means that the highest element
number you can specify is 8.
There are two primary ways to work with text in Java: a string or an array of characters.
When you're working with strings, one useful technique is to put each character in a string
into its own element of a character array. To do this, call the string's toCharArray() method,
which produces a char array with the same number of elements as the length of the string.
This hour's first project is an application that uses both of the techniques introduced in this
section. The NoSpaces program displays a string with all space characters (' ') replaced with
periods ('.').
Enter the text of Listing 9.1 in your word processor and save the file as NoSpaces.java.
The NoNames application stores the text Rudolph the Red-Nosed Reindeer in two places: a
string called mostFamous, and a char array called mfl. The array is created in Line 4 by
calling the toCharArray() method of mostFamous, which fills an array with one element for
each character in the text. The character R goes into element 0, u into element 1, d into
element 2, and so on, up to r in element 29.
The for loop in Lines 5–12 looks at each character in the mfl array. If the character is not a
space, it is displayed. If it is a space, a . character is displayed instead.
Multidimensional Arrays
The arrays you have been introduced to thus far in the hour all have one dimension, so you
can retrieve an element using a number ranging from 0 to the largest element number in the
array. Some types of information require more dimensions to store adequately as arrays. An
example would be the (x,y) coordinate system. If you needed to store a list of x and y
coordinates that have a point marked on them, you could use a two-dimensional array. One
dimension of the array could store the x coordinate, and the other dimension could store the y
coordinate.
To create an array that has two dimensions, you must use an additional set of square brackets
when creating and using the array. Consider the following:
boolean[][] selectedPoint = new boolean[50][50];
selectedPoint[4][13] = true;
selectedPoint[7][6] = true;
selectedPoint[11][22] = true;
This example creates an array of Boolean values called selectedPoint. The array has 50
elements in its first dimension and 50 elements in its second dimension, so there are 2,500
individual array elements that can hold values (50 multiplied by 50). When the array is
created, each element is given the default value of false. Three elements are then given the
value of true: a point at the (x,y) position of (4,13), one at (7,6), and one at (11,22).
Arrays can have as many dimensions as you need, but keep in mind that they take up a lot of
memory if they're extremely large. Creating the 50 x 50 selectedPoint array was equivalent to
creating 2,500 individual variables.
Sorting an Array
When you have grouped a bunch of similar items together into an array, one of the things you can do
easily is rearrange items. The following statements switch the values of two elements in an integer
array called numbers:
These statements result in numbers[5] and numbers[6] trading values with each other. The integer
variable called temp is used as a temporary storage place for one of the values being swapped.
The most common reason to rearrange elements of an array is to sort them into a specific order.
Sorting is the process of arranging a list of related items into a set order. An example would be sorting
a list of numbers from lowest to highest.
Santa Claus, the world's biggest user of lists, might want to use sorting to rearrange the order of gift
recipients according to last name. This order could determine who receives gifts first on Christmas
Eve, with people such as Willie Aames and Paul Azinger ranking in their Yuletide plunder much
earlier than alphabetical unfortunates such as Dweezil Zappa and Jim Zorn. (As someone whose last
name begins with "C," I'm not necessarily opposed to this practice).
Sorting an array is easy in Java because the Arrays class does all of the work for you. Arrays, which is
part of the java.util group of classes, can rearrange arrays of all variable types as well as strings.
To use the Arrays class in a program to sort an array, undertake the following steps:
Use the import java.util.*; statement to make all of the java.util classes available in the
program.
An array of variables that is sorted by the Arrays class will be rearranged into ascending numerical
order. This will be easy to see with an array of numbers such as float values. Characters and strings
will be arranged according to the alphabet, with the first letters such as A, B, and C coming first, and
the last letters such as X, Y, and Z coming last.
Listing 9.2 contains a short program that sorts five names. Enter this with your word processor and
save the file as Name.java. Make sure not to overlook Line 1. If you do, the program will fail to
compile because the Arrays class in Line 11 can't be found.
1: import java.util.*;
2:
3: class Name {
4: public static void main(String[] arguments) {
5: String names[] = { "Peter", "Patricia", "Hunter", "Sarah",
6: "Gabe", "Gina", "Rob", "John", "Zoey", "Tammy", "Robert",
7: "Sean", "Paschal", "Kathy", "Neleh", "Vecepia" };
8: System.out.println("The original order:");
9: for (int i = 0; i < names.length; i++)
10: System.out.println(i + ": " + names[i]);
11: Arrays.sort(names);
12: System.out.println("The new order:");
13: for (int i = 0; i < names.length; i++)
14: System.out.println(i + ": " + names[i]);
15: }
16: }
After you have created this source file, compile it. Using the SDK, you can compile it at a command
line by entering this command:
javac Name.java
This Java program displays a list of five names in their original order, sorts the names, and then
redisplays the list.
When you're working with strings and the basic types of variables such as integers and floating-point
numbers, you can only sort them by ascending order using the Arrays class. You can write code to do
your own sorts by hand if you desire a different arrangement of elements during a sort, or if you want
better efficiency than the Arrays class provides.
Summary
Arrays make it possible to store complicated types of information in a program and manipulate that
information. They're ideal for anything that can be arranged in a list and can be accessed easily using
the loop statements that you learned about during Hour 8, "Repeating an Action with Loops."
To be honest, the information processing needs of Santa Claus probably have outgrown arrays. There
are more children being manufactured each year, and the gifts they want are increasing in complexity
and expense. Pokémon alone created a logistical nightmare at the North Pole.
Your programs are likely to use arrays to store information that is unwieldy to work with using
variables, even if you're not making any lists or checking them twice.