8.2 Using Arrays

Having seen how to create arrays, let us now examine some of the ways that we can operate on them and their elements.

The elements of an array can be treated like any other variable of that type. We can assign values to them, print them, use them in expressions, and so on.

Often we want to perform some operation on every element of an array. We sometimes refer to this as indexing through the array.

Example 1

If we wanted to create an array called flags containing 100 boolean values all set to true (rather than the standard initialization to false), we could write
 boolean[] flags = new boolean [100];
   for (int i 0; i < flags.length; i++)
      flags[i] = true;

In the example, we used a for statement to index through the array. We could have used a while or a do but the for is simplest. It is almost always the case that a for is the best way to index through an array. Notice also the use of flags.length to determine the upper bound. This is more reliable and probably clearer to a reader than using the value 100.

Finally, note the way that we have written the condition that controls the loop - as i < flags.length. The value of flags.length is the size of the array - the number of elements in it. As we have already noted, since an array is indexed from zero, the index of the last element is one less than the value of its length. If we were to write the condition as i <= flags.length, then we would be trying to access an element off the end of the array. If we attempt to use an index value that is out of the range of an array, Java rewards us by throwing an ArraylndexOutOfBoundsException.(Note: See Appendix E for notes on exception handling.)

Because arrays, like other objects, are reference types, they behave in similar ways when we try to manipulate them. As an example, suppose that we make the following declarations:

   int[] p = {1,3,5,7,9};
   int[] q = {0,2,4,6,8}; 

to give us the situation pictured in the next diagram.

	

If we were now to write the assignment statement

	p = q;

this would copy the value from the cell labelled q in the diagram to the one labelled p. The effect of this would be to have p refer to the same array as q. Since there is no longer any reference to the array of odd numbers, they are no longer accessible to the program.

	

Comparison of arrays is like comparison of other objects in that, if p and q are array variables, the expression p == q will be true if and only if both p and q are referring to the same array cells. It is not a test of the equality of the elements of two distinct arrays. If we wanted to test for equality of the contents of two arrays, we could use a loop that indexed through the arrays comparing corresponding pairs.(Note: Java contains a method Arrays.equals in the java.util package that compares equality of content of arrays.)

Arrays, like all objects, can be parameters of methods and can be returned by methods.

Example 2

The method join creates a new array that contains the elements of each of the method's parameters and returns a reference to that array.
public static double[] join (double[] a, double[] b)
{
   double[] result = new double [a.length + b.length];
   int i, j;
   for (i = 0; i < a.length; i++)
      result[i] =a[i];
   for (j = 0; j < b.length; i++, j++)
      result[i] = b[j] ;
   return result;
}

As usual, Java passes parameters by value but, with arrays, the values that are passed are references to the arrays. This means that methods have the ability to alter the contents of arrays that are passed as parameters.

Example 3

The method swap shown here will switch the values of two elements in an array of double values.

public static void swap (double[] list, int i, int j)
{
   double temp list[i];
   list[i] = list[j];
   list[j] = temp;
}

To show the effect of swap, suppose we have an array masses shown below.

 

If we then write the statement

 swap(masses,1,4);

the values at masses[1] and masses[4] will be switched.

 

Exercise 8.2

  1. What would be printed by the following program fragment?
       int[] list = new int[4];
       for (int i = 0; i < list.length; i++)
       list[i] = 3 - i;
       System.out.println(list[1]+2);
       System.out.println(list[1+2]);
       System.out.println(list[1]+list[2]);
  2. Suppose that an array sample has been declared as follows:
       int[] sample = new int[SIZE];
    Write one or more statements to perform each task.
    (a) Initialize all elements of the array to one.
    (b) Switch the values at either end of the array.
    (c) Change any negative values to positive values (of the same magnitude).
    (d) Set the variable sampleSum to the sum of the values of all the elements.
    (e) Print the contents of the odd-numbered locations.

  3. Write a method max that has one double array parameter. The method should return the value of the largest element in the array.

  4. Complete the definition of the method equals so that it returns true if and only if its two array parameters contain equal elements.
       public static boolean equals (double[] a, double[] b)
  5. Write a program that repeatedly prompts the user to supply scores (out of 10) on a test. The program should continue to ask the user for marks until a negative value is supplied. Any values greater than ten should be ignored. Once the program has read all the scores, it should produce a table with the following headings:
    	Score 		# of Occurrences
    The program should then calculate the mean score, rounded to one decimal place.