




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





An array is a compound data structure where each element is identified by an index. You can make an array of ints, doubles, or any other type, but all the values in an array have to have the same type. Syntactically, arrays types look like other Java types except they are followed by []. For example, int[] is the type “array of integers” and double[] is the type “array of doubles.” You can declare variables with these types in the usual ways:
int[] count; double[] values;
Until you initialize these variables, they are set to null. To create the array itself, use the new command.
count = new int[4]; values = new double[size];
The first assignment makes count refer to an array of 4 integers; the second makes values refer to an array of doubles. The number of elements in values depends on size. You can use any integer expression as an array size. The following figure shows how arrays are represented in state diagrams:
The large numbers inside the boxes are the elements of the array. The small numbers outside the boxes are the indices used to identify each box. When you allocate a new array of integers, the elements are initialized to zero.
9.1 Accessing elements
To store values in the array, use the [] operator. For example count[0] refers to the “zeroeth” element of the array, and count[1] refers to the “oneth” element. You can use the [] operator anywhere in an expression:
count[0] = 7; count[1] = count[0] * 2; count[2]++; count[3] -= 60;
All of these are legal assignment statements. Here is the effect of this code fragment:
7 14 1 -
The indices of an array start with 0. For perverse reasons, computer scien- tists always start counting from zero. So, the four elements of this array are numbered from 0 to 3, which means that there is no element with the index 4. It is a common error to go beyond the bounds of an array, which will cause an ArrayOutOfBoundsException. As with all exceptions, you get an error message and the program quits. You can use any expression as an index, as long as it has type int. One of the most common ways to index an array is with a loop variable. For example:
int i = 0; while (i < 4) { System.out.println (count[i]); i++; }
This is a standard while loop that counts from 0 up to 4, and when the loop variable i is 4, the condition fails and the loop terminates. Thus, the body of the loop is only executed when i is 0, 1, 2 and 3. Each time through the loop we use i as an index into the array, printing the ith element. This type of array traversal is very common. Arrays and loops go together like fava beans and a nice Chianti.
9.2 Copying arrays
When you copy an array variable, remember that you are copying a reference to the array. For example:
except that it is more concise and, since it puts all the loop-related statements in one place, it is easier to read. For example:
for (int i = 0; i < 4; i++) { System.out.println (count[i]); }
is equivalent to
int i = 0; while (i < 4) { System.out.println (count[i]); i++; }
As an exercise, write a for loop to copy the elements of an array. As another exercise, write a for loop that traverses an IntList.
9.4 Arrays and objects
In many ways, arrays behave like objects:
Some of the objects we have looked at, like Rectangles, are similar to arrays, in the sense that they are named collection of values. This raises the question, “How is an array of 4 integers different from a Rectangle object?” If you go back to the definition of “array” at the beginning of the chapter, you will see one difference, which is that the elements of an array are identified by indices, whereas the elements (instance variables) of an object have names (like x, width, etc.). Another difference between arrays and objects is that all the elements of an array have to be the same type. Although that is also true of Rectangles, many objects have instance variables with different types,
9.5 Array length
Actually, arrays do have one named instance variable: length. Not surprisingly, it contains the length of the array (number of elements). It is a good idea to use this value as the upper bound of a loop, rather than a constant value. That way, if the size of the array changes, you won’t have to go through the program changing all the loops; they will work correctly for any size array.
for (int i = 0; i < a.length; i++) { b[i] = a[i]; }
The last time the body of the loop gets executed, i is a.length - 1, which is the index of the last element. When i is equal to a.length, the condition fails and the body is not executed, which is a good thing, since it would cause an exception. This code assumes that the array b contains at least as many elements as a. As an exercise, write a method called cloneArray that takes an array of integers as a parameter, creates a new array that is the same size, copies the elements from the first array into the new one, and then returns a reference to the new array.
9.6 Random numbers
Most computer programs do the same thing every time they are executed, so they are said to be deterministic. Usually, determinism is a good thing, since we expect the same calculation to yield the same result. For some applications, though, we would like the computer to be unpredictable. Games are an obvious example, but there are many more. Making a program truly nondeterministic turns out to be not so easy, but there are ways to make it at least seem nondeterministic. One of them is to generate random numbers and use them to determine the outcome of the program. Java provides a built-in method that generates pseudorandom numbers, which are not truly random in the mathematical sense, but for our purposes, they will do. Check out the documentation of the random method in the Math class. The return value is a double between 0.0 and 1.0. Each time you invoke random you get a different randomly-generated number. To see a sample, run this loop:
for (int i = 0; i < 10; i++) { double x = Math.random (); System.out.println (x); }
To generate a random double between 0.0 and an upper bound like high, you can multiply x by high. How would you generate a random number between low and high? How would you generate a random integer?
9.7 Two-Dimensional Arrays
So far we have only looked at one-dimensional arrays—a sequence of elements all of the same type. Well there’s no reason those elements can’t be arrays themselves. An array of arrays is a two-dimensional array.
9.8 The Vector class
One of the problems with arrays is that their size is fixed. If you try to access something past the end of an array, it causes a run-time error. So it is up to the programmer to keep track of the size of the array and resize it when necessary. Another problem is that all the elements of the array have to have the same type. We can solve both of these problems by replacing the array with a Vector. The Vector is a built-in Java class in the java.util package. The ele- ments of a Vector can be any kind of Object, and you can mix different objects within a single Vector. Also, Vectors resize themselves automatically as you add elements. The Vector class provides methods named get and set that are equivalent to the bracket syntax we use to access the elements of an array. You should review the other Vector operations by consulting the online documentation. Before using the Vector class, you should understand a few concepts. Every Vector has a capacity, which is the amount of space that has been allocated to store values, and a size, which is the number of values that are actually in the vector. The following figure is a simple diagram of a Vector that contains three elements, but it has a capacity of seven.
In general, it is your responsibility to make sure that the vector has sufficient size before invoking set or get. If you try to access an element that does not exist (in this case the elements with indices 3 through 6), you will get an ArrayIndexOutOfBounds exception. The Vector methods add and insert automatically increase the size of the Vector, but set does not. The resize method adds null elements to the end of the Vector to get to the given size. Most of the time you don’t have to worry about capacity. Whenever the size of the Vector changes, the capacity is updated automatically. For performance reasons, some applications might want to take control of this function, which is why there are additional methods for increasing and decreasing capacity. Because we don’t have access to the implementation of a vector, it is not clear how we should traverse one. Of course, one possibility is to use a loop variable as an index into the vector:
for (int i=0; i<v.size(); i++) { System.out.println (v.get(i)); }
There’s nothing wrong with that, but there is another way that serves to demon- strate the Iterator class. Vectors provide a method named iterator that returns an Iterator object that makes it possible to traverse the vector.
9.9 The Iterator class
Iterator is an abstract class in the java.util package. It specifies three methods:
hasNext: Does this iteration have more elements?
next: Return the next element, or throw an exception if there is none.
remove: Remove from the collection the last element that was returned.
The following example uses an iterator to traverse and print the elements of a vector.
Iterator iterator = v.iterator (); while (iterator.hasNext ()) { System.out.println (iterator.next ()); }
Once the Iterator is created, it is a separate object from the origi- nal Vector. Subsequent changes in the Vector are not reflected in the Iterator. In fact, if you modify the Vector after creating an Iterator, the Iterator becomes invalid. If you access the Iterator again, it will cause a ConcurrentModification exception. Iterators make it possible to traverse a data structure without knowing the details of its implementation. In fact, there are other Java classes that provide Iterators; we can traverse any of them without even knowing what kind of object we have.
9.10 Glossary
array: A named collection of values, where all the values have the same type, and each value is identified by an index.
collection: Any data structure that contains a set of items or elements.
element: One of the values in an array. The [] operator selects elements of an array.
index: An integer variable or value used to indicate an element of an array.
deterministic: A program that does the same thing every time it is invoked.
pseudorandom: A sequence of numbers that appear to be random, but which are actually the product of a deterministic computation.