Common Array Algorithms

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: Common Array Algorithms
Printed by: Guest user
Date: Wednesday, October 30, 2024, 3:21 PM

Description

This chapter discusses how a for loop can be used to iterate over the elements of a one-dimensional array. In addition, it also discusses enhanced for loops. The chapter demonstrates the use of arrays to solve common problems such as finding sum, average, maximum, and minimum values of numbers stored in array. Pay attention to some of the common programming errors one can make while using arrays.

1. Common Array Algorithms

lineOfBoxesAn array that uses a single subscript is called a one dimensional array. This is because one index is used to access the values in the array. Its cells are like numbered boxes lined up one after the other in a line.

A two dimensional array requires two indexes to access values. Its cells are like boxes arranged into a rectangle. Arrays of even higher dimension are possible, although rarely used. This chapter discusses typical ways to use one dimensional arrays.


Chapter Topics:

      • Arrays and counting loops
      • Enhanced for loop
      • The length of an array
      • Finding the maximum and minimum of an array of numbers
      • Finding the sum of the elements of an array
      • Computing the average of the elements of an array

Question 1:

How could you print out every element of an array with 100 cells?


Source: Bradley Kjell, http://programmedlessons.org/Java9/chap61/ch61_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.

2. Counting Loops and Arrays


Answer:

This sounds like a good place for a counting loop.

Counting Loops and Arrays

public class CountArray
{

  public static void main ( String[] args )
  {
    int[] egArray = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 };

    for ( int index =  ;  ;  )
    {
      System.out.println(  );
    }
  }
}

In Java, the index of an array starts at 0 and counts up to one less than the number of elements in the array. Counting loops can easily do that. The example program (above) does that, except for a blank or two.

The variable egArray refers to an array object that has been constructed using an initializer list.


Question 2:

Fill in the blanks so that the program prints out every element, in order. You may wish to copy and paste from the following:

    0 index++ egArray[index] index < 10

(Highlight a string and then use use "copy" and "paste" commands from the "edit" menu of your browser to paste the string into a blank. Or use control-c and control-v as shortcuts for copy and paste.)

3. The length of an Array


Answer:

public class CountArray
{

  public static void main ( String[] args )
  {
    int[] egArray = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 };

    for ( int index= 0 ; index < 10 ; index++ )
    {
      System.out.println( egArray[ index ] );
    }
  }
}

The length of an Array

It is annoying to count the elements in an array. Worse, when you write a program you may not know in advance how many elements are needed. Array objects are created as the program runs. Often, the length of the array depends on data, and different runs of the program may process data that require different lengths of arrays.

Luckily, as it is running your program can determine how many elements an array has. The length instance variable of an array is the number of cells it has.

The for statement can be written like this:

for ( int index= 0 ; index < egArray.length; index++ )

Lines of code similar to the above are very common. Programs often use several arrays, and often "visit" each element of an array, in order.


Question 3:

Fill in the blanks below so that the elements of egArray are visited in reverse order, starting with the last element and counting down to element 0. (Copy and paste strings from anywhere on this page, if you want.)

for ( int index=  ;  ;  )

I bet that you get this question wrong!

4. Reading in Each Element


Answer:

for ( int index= egArray.length-1 ; index >= 0 ; index-- )

I win! You forgot the -1. Off-by-one errors of this kind are very common. It was an easy bet. super bug

Reading in Each Element

Here is a program that prompts the user for each element of an array and reads it in. The array is hard coded to be five elements long. After it is filled with data, the array is written to the monitor.

Usually a program would do something with the data (besides just print it out) after it was read in. This would usually involve more loops.

import java.util.Scanner ;

public class InputArray
{

  public static void main ( String[] args )
  {

    int[] array = new int[5];
    int   data;

    Scanner scan = new Scanner( System.in );

    // input the data
    for (  ;  ;  )
    {
      System.out.println( "enter an integer: " );
      data = scan.nextInt();
      array[ index ] = data ;
    }
      
    // write out the data
    for (  ;  ;   )
    {
      System.out.println( "array[ " + index + " ] = " + array[ index ] );
    }

  }
}      

Question 4:

Fill in the blanks so that the program works as described. You may wish to copy and paste some of the following phrases. (Hint: you will need to use most phrases twice.)

int index
index <
= 0
index++
array.length

5. Complete Program


Answer:

The complete program is given below.

Complete Program

Notice that the two for statements are the same. This is very common. It would be nice to copy this program to a file and to run it. When you do this, change the length of the array (the 5) to some other value (say, 9) and note the effect.

Review: Recall that the scope of the identifier index declared in the for statement is limited to just the body of its loop. So in the program, there are two variables, each named index, and each limited in scope to the body of its own for.

import java.util.Scanner ;

class InputArray
{

  public static void main ( String[] args )
  {

    int[] array = new int[5];
    int   data;

    Scanner scan = new Scanner( System.in );

    // input the data
    for ( int index=0; index < array.length; index++ )
    {
      System.out.println( "enter an integer: " );
      data = scan.nextInt();
      array[ index ] = data ;
    }
      
    // write out the data
    for ( int index=0; index < array.length; index++ )
    {
      System.out.println( "array[ " + index + " ] = " + array[ index ] );
    }

  }
} 

Question 5:

The variable data is not really needed in this program. Mentally change the program so that this variable is not used.

6. Run-time Array Length


Answer:

The two lines:

      data  = scan.nextInt();
      array[ index ] = data ;

can be replaced by the single line:

       array[ index ] = scan.nextInt();

And then the declaration int data; should be removed.

Run-time Array Length

An array object is constructed as the program runs (as are all objects). When an array is constructed, its size can be in a variable.

Here is the previous example, with some modifications:

import java.util.Scanner ;

class InputArray
{

  public static void main ( String[] args )
  {

    int[] array;
    int   data;
    Scanner scan = new Scanner( System.in );

    // determine the size and construct the array
    System.out.print( "What length is the array? " );
    int size = scan.nextInt();

    array  = new int[  ]; 

    // input the data
    for ( int index=0; index < array.length; index++)
    {
      System.out.print( "enter an integer: " );
      array[ index ] = scan.nextInt();
    }
      
    // write out the data
    for ( int index=0; index < array.length; index++ )
    {
      System.out.println( "array[ " + index + " ] = " + array[ index ] );
    }

  }
} 

Question 6:

Fill in the blank.

7. Minimum and Maximum


Answer:

array = new int[ size ];  

Minimum and Maximum

numberLine

The largest integer in a list of integers is the maximum value. The maximum may occur several times, but no other integer in the list is larger. Look at the following:

2, 9, 52, 23, -19, 23, 17, -45, 0

The integer 52 is the maximum. If you plot these integers on a number line the maximum is the last one on the right.

Similarly, the smallest integer in the list is the minimum. The minimum may occur several times. In the above list, the minimum is -45. The minimum is the last number on the left of the number line.

Question 7:

Examine the following collection of integers:

-20, 19, 1, 27, 5, -1, 27, 19, 5
  1. What is the maximum of the collection?
  2. How did you figure this out?

8. Finding the Maximum of an Array


Answer:

-20, 19, 1, 27, 5, -1, 27, 19, 5
  1. What is the maximum of the collection?
    • 27
  2. How did you figure this out?
    • By scanning over the integers left to right and mentally keeping track of the largest seen so far.

Finding the Maximum of an Array

A systematic procedure used to compute something is called an algorithm. The procedure described in the answer is an algorithm for finding the maximum of a list. An algorithm is a description of how to do something. It is not tied to any particular language. For example, you (possibly) followed the above algorithm when you mentally examined the list. An algorithm can be implemented in any computer programming language. The example program shows the above algorithm.

The variable max plays the role of the largest integer seen so far. The program scans elements of the array starting at index 0 and going to the end.

The variable max should be initialized to a value that is guaranteed to be no larger than the maximum element of the array. A program should always work correctly, regardless of the quirks of the data. Don't make assumptions about what the data look like. (The initializer list is only for a convenience in this example. A typical program would get its data from the user or from a file.)

class MaxAlgorithm
{

  public static void main ( String[] args ) 
  {

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   max;

    // initialize the current maximum
 
    max =  ;

    // scan the array
    for ( int index=0; index < array.length; index++ )
    {
     
        <more stuff goes here>


    }
      
    System.out.println("The maximum of this array is: " + max );

  }
}    

Question 8:

Fill in the blank so that max is initialized to a value that is guaranteed to be no larger than the maximum element of the array, no matter what values are in the initializer list.

9. Classic Bug (1): Initializing Max Incorrectly


Answer:

The first (index 0) element in an array will never be larger than the maximum element in that array. (It might be the maximum element of the array; but this is fine.)

    max = array[0];

This code assumes that there is at least one element in the array. If there is not, the java system will detect that the index "0" is out of bounds and throw an exception.

Classic Bug (1): Initializing Max Incorrectly

Classic Bug (1): It is tempting to initialize max to something you think is much less than the maximum, like -999. However, in doing so you make a risky assumption about the data. Perhaps the array holds the national debt for each of the last ten years. All these values are negative, and -999 would easily exceed the true maximum.

Examine the program. Notice how max is initialized to the first element in the array (at index 0). This assumes that the array exists and that it has at least one element. For the present program this is a safe assumption (but might not be in other situations.)

The for loop is set up to look at every element in the array, starting with the first element in cell 0, to see if that element is larger than the current maximum.

It would be OK (and perhaps preferable) to start out index at 1 since index 0 was used to initialize max. But the program as written works fine (as soon as you fill in the blank).

class MaxAlgorithm
{

  public static void main ( String[] args ) 
  {

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   max;

    // initialize the current maximum
 
    max = array[0];

    // scan the array
    for ( int index=0; index < array.length; index++ )
    {
     
      if (  )  // examine the current element

        max = array[ index ];        // if it is the largest so far, change max

    }
      
    System.out.println("The maximum of this array is: " + max );

  }
}   

Question 9:

Complete the program.

10. Complete Max Program


Answer:

The complete program is given below.

Complete Max Program

Here is the program. Examine how the if statement changes max.

class MaxAlgorithm
{

  public static void main ( String[] args ) 
  {

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   max;

    // initialize the current maximum
    max = array[0];

    // scan the array
    for ( int index=0; index < array.length; index++ )
    { 
      if ( array[ index ] > max )    // examine the current element
        max = array[ index ];        // if it is the largest so far, change max

    }
      
    System.out.println("The maximum of this array is: " + max );
  }
}      

Question 10:

What is the maximum of this list of integers:

-45,  -23,  -87,  -56,  -92,  -12,  -36

11. Classic Bug (2): Big Negatives


Answer:

The maximum is   -12.

Classic Bug (2): Big Negatives

numberLineTwo

Classic Bug (2): It is tempting to say that the maximum is -92, since -92 seems to be a bigger number than -12. But this confuses the absolute value of a number with its position on the number line. If you are looking for the maximum of a list of numbers, you are looking for the number which is furthest to the right on the number line, even if the number is negative.

Think of this as pay. If Jill is paid -92 dollars a day and Joe is paid -12 dollars a day, who is paid the most? (And exactly which fast food restaurant do they work at?)

The minimum of a list of numbers is the one furthest to the left on the number line.

Question 11:

What is the minimum of our list of integers:

-45,  -23,  -87,  -56,  -92,  -12,  -36

12. Breaking the Program


Answer:

-92

Breaking the Program

class MaxAlgorithm
{
  public static void main ( String[] args ) 
  {
    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   max;

    // initialize the current maximum
    max = array[0];

    // scan the array
    for ( int index=0; index < array.length; index++ )
    { 
      if ( array[ index ] > max )    // examine the current element
        max = array[ index ];        // if it is the largest so far, change max
    }     
    System.out.println("The maximum of this array is: " + max );
  }
}

Debugging a program is often difficult. Finding test cases that thoroughly test a program is an important part of this.

Of course, testing must be done with an actual running program and with actual data. Running a program once, with "toy" data, and saying that it works is not good enough for professional program development.

Compile and run the program. Once you have it running see if you can "break" it by initializing the array to different values, such as the following:

      • Put the largest element at the beginning.
      • Put the largest element at the end.
      • Put in more than one copy of the largest element.
      • Put in an extremely large element.
      • Make all elements the same.
      • Make all elements negative.
      • Make all elements zero.

Is the correct maximum found in each case? Sometimes a program works for the data a programmer was thinking about when the program was written, but not for all the kinds of data the program is used with. This is why testing software often involves people other than those who wrote it.

Question 12:

Here is an interesting situation: change the test part of the for to

index < array.length-1

Now run the program again on the above test cases.

  1. Will the buggy program (with the changed loop) find the correct maximum of the data that is given in the original initializer list?
  2. When will the program not work correctly?
  3. Is it obvious that there is a bug?

13. Classic Bug (3): Overlooking Boundaries


Answer:

  1. Will the buggy program (with the changed loop) find the correct maximum of the data that is given in the original initializer list?
    • Yes—for this particular set of data, the program will compute the correct maximum.
  2. When will the program not work correctly?
    • When the maximum element of the array is in the very last cell (and only occurs once in the array.)
  3. Is it obvious that there is a bug?
    • No—for most data the program works OK. If it were tested just a few times, it might pass every test.

Classic Bug (3): Overlooking Boundaries

The change to the program introduces an off-by-one error. The array index does not go far enough to test the last cell of the array.

With a ten-element initializer list, the above buggy program will fail about one time in ten (assuming random lists of data). Failure might not be obvious, because the answer it computes is close to the maximum. With a ten thousand element array, the program will fail about one time in ten thousand! Sloppy testing will never find this bug. Off-by-one errors can be very subtle.

Classic Bug (3): Not testing the "boundaries". Bugs are often found at the boundaries: at the beginning and ends of loops, at the beginning and ends of data, with large or small values (or zero), with a very large amount of data, or with no data at all (which should not break the program).

Question 13:

What happens when the following code is run?

    int[] myWeeklyPay = {769, 588, 1245, 309, 388, 902}; int sum = 0; for ( int j=0; j<=6; j++ ) sum += myWeeklyPay[j];

14. Enhanced for loop


Answer:

The index j goes one cell too far. An ArrayIndexOutOfBoundsException will be thrown and you program will be halted.

Off-by-one errors are very common. A running Java program checks each array index before it is used to be sure it is within bounds.

Enhanced for loop

class MaxAlgorithm
{
  public static void main ( String[] args ) 
  {

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   max;

    // initialize the current maximum
    max = array[0];

    // scan the array
    for ( int value : array )
    { 
      if ( value > max )    // examine the current element
        max = value ;         // if it is the largest so far, change max
    }
      
    System.out.println("The maximum of this array is: " + max );
  }
}


Java has an enhanced for loop that visits each element of an array in order. It automatically avoids off-by-one bugs. Study the program (above). The program does the same thing as the previous program, but with different syntax.

(There is a colon : separating value and array in the above. This might be hard to see in your browser.)

To read this code out loud say: "For each value in array, ..."

Sometimes the enhanced for loop is called a foreach loop.

The enhanced for loop

for ( int value : array )
{
}

assigns to value the contents of each cell of the array starting with cell zero and going in order up to the last cell of the array. For each assignment, the loop body is executed. With this enhanced for loop there is no danger of an index that might go out of bounds, nor any danger of skipping the first or last element.

Question 14:

Must the enhanced for loop start with the first (index 0) element of the array?

15. Finding the minimum in an Array


Answer:

Yes.

Finding the minimum in an Array

Here is a program that finds the minimum of an array. It is similar to the maximum-finding program:

class MinAlgorithm
{

  public static void main ( String[] args ) 
  {

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   min;

    // initialize the current minimum
     ;

    // scan the array
    for ( int index=0; index < array.length; index++ )
    { 
      if  

         ;

    }
      
    System.out.println("The minimum of this array is: " + min );
  }
}


Question 15:

Fill in the blanks. Select from the following phrases.

min = array[8]
min = array[0]
min = array[ index ]
array[ index ] == min
array[ index ] > min
array[ index ] < min
index++

You can copy and paste from the phrases into the blanks. (Hint: only some of the phrases are used.)

16. The complete program is given below.


Answer:

Yes.

Complete Minimum-finding Program

As with the maximum-finding program, the trial minimum is initialized to the first (index 0) element of the array. Then it is updated as needed as each element of the array is inspected in the loop.

class MinAlgorithm
{

  public static void main ( String[] args ) 
  {

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   min;

    // initialize the current minimum
    min = array[ 0 ];

    // scan the array
    for ( int index=0; index < array.length; index++ )
    { 
      if ( array[ index ] < min )

        min = array[ index ] ;

    }
      
    System.out.println("The minimum of this array is: " + min );
  }
}


Question 16:

Could an enhanced for loop be used in this program?

17. Enhanced Minimum Program


Answer:

Yes.

Enhanced Minimum Program

Here is the minimum-finding program, now using an enhanced for loop:

class MinAlgorithm
{

  public static void main ( String[] args ) 
  {

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   min;

    // initialize the current minimum
    min =  

    // scan the array
    for (     )
    { 
       if (    < min ) 

         min =  ; 

    }
      
    System.out.println("The minimum of this array is: " + min );
  }
} 


Question 17:

Fill in the blanks. Select from the following phrases.

array
array[8]
int val
val
array[0]
array[ index ]
index++
:

(Hint: only some of the phrases are used.)

18. Summing the numbers in an Array


Answer:

class MinAlgorithm
{
  public static void main ( String[] args ) 
  {
    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   min;

    // initialize the current minimum
    min = array[0]; 

    // scan the array
    for ( int val : array )
    { 
       if (   val < min ) 
         min = val ; 
    }
      
    System.out.println("The minimum of this array is: " + min );
  }
}         

Summing the numbers in an Array

Say that you want to compute the sum of a list of numbers. This algorithm sounds much like those of the previous two programs.

The sum is initialized to zero. Then the loop adds each element of the array to the sum.

You could initialize the sum to the first number and then have the loop add the remaining numbers. But there is no advantage in doing this.

Here is the program. The array contains values of type double. Assume that the array contains at least one element.


class SumArray
{

  public static void main ( String[] args ) 
  {
    double[] array =  { -47.39, 24.96, -1.02, 3.45, 14.21, 32.6, 19.42 } ;

    // declare and initialize the total
        total =       ;

    // add each element of the array to the total
    for ( int index=0; index < array.length; index++ )
    { 

      total =     ;

    }
      
    System.out.println("The total is: " + total );
  }
}


Question 18:

Complete the program by filling in the blanks.

19. Complete Summing Program


Answer:

The complete program is given below.

Complete Summing Program


class SumArray
{

  public static void main ( String[] args ) 
  {
    double[] array =  { -47.39, 24.96, -1.02, 3.45, 14.21, 32.6, 19.42 } ;

    // declare and initialize the total
    double    total = 0.0 ;

    // add each element of the array to the total
    for ( int index=0; index < array.length; index++ )
    { 
      total =  total + array[ index ]  ;

    }
      
    System.out.println("The total is: " + total );
  }
} 


The variable total is declared to be of type double because the elements in the array are doubles, as is their sum. total is initialized to zero. Sums should always be initialized to zero.

(You could, perhaps, initialize total to the first element of the array, and then use the loop to add in the remaining elements. But this is much less clear than the expected way of doing things and is an open invitation to bugs.)

The program visits each element of the array, in order, adding each to the total. When the loop exits, total will be correct. The statement

total =  total + array[ index ]  ;

would not usually be used. It is more common to use the += operator:

total += array[ index ]  ;

Question 19:

The program could be written with an enhanced for loop. Replace the for loop in the above program:

for (  val :  )

Now replace the loop body:

 +=  ;

20. Sum of No Elements


Answer:

for ( double val : array )
total += val ;

Sum of No Elements

Here is the revised program:

class SumArrayRevised
{

  public static void main ( String[] args ) 
  {
    double[] array =  {} ;

    // declare and initialize the total
    double total =    0.0 ;

    // add each element of the array to the total
    for ( double val : array )
      total += val ;
      
    System.out.println("The total is: " + total );
  }
} 

Question 20:

But the array has no elements!!   Will the program compile?   Will the program run?   What is the sum of an array with no elements?

21. Computing the Average


Answer:

The program will compile and run. The array object will be constructed successfully (but it will have no cells and no values).

The enhanced for loop will run correctly (but it will not assign anything to val and will never execute its loop body.)

The program will print out:

    The total is: 0.0

This is a dubious claim. A better program would test for zero-length arrays and treat them as a special case. Our next program will do that.

Computing the Average

Here is the program with some additional statements for computing the average of the elements. It checks that there are more than zero elements and avoids dividing by zero.

You might think that it is strange to test if array contains any elements, since it is obvious that it does. However, in a more realistic program the array would come from an external source (perhaps from a file), and might contain no elements. The data might come from a human user, and sometimes humans make errors (this might come as a shock.)


public class AverageArray
{
  public static void main ( String[] args ) 
  {
    double[] array =  { -47.39, 24.96, -1.02, 3.45, 14.21, 32.6, 19.42 } ;

    if ( array.length  0 )
    {
      // declare and initialize the total
      double  total = 0.0 ;

      // add each element of the array to the total
      for ( double x : array )
        total += x ;
        
      System.out.println("The total is:   " + total );
      System.out.println("The average is: " + total /   );
    }      
    else
      System.out.println("The array contains no elements." );  
  }
}

Question 21:

Fill in the blanks.

22. Array Equality


Answer:

if ( array.length > 0 )
{
  . . .
  System.out.println("The average is: " + total / array.length  );
}      
else
  System.out.println("The array contains no elements." );

Array Equality

Are the following two arrays equal?

int[] arrayA = { 1, 2, 3, 4 };
int[] arrayB = { 7, 8, 9};

Obviously not.

Are these two arrays equal?

int[] arrayC = { 1, 2, 3, 4 };
int[] arrayD = { 4, 3, 2, 1 };

Less obvious, but ordinarily they would not be regarded as equal.

What about these two arrays: are they equal?

int[] arrayE = { 1, 2, 3, 4 };
int[] arrayF = { 1, 2, 3, 4 };

Here, it depends on what you mean by "equal". The object referred to by the variable arrayE is not the same object that is referred to by the variable arrayE. The "alias detector" == returns false.


                     
class ArrayEquality
{
  public static void main ( String[] args )
  {
    int[] arrayE = { 1, 2, 3, 4 };
    int[] arrayF = { 1, 2, 3, 4 };
    
    if (arrayE==arrayF)
      System.out.println( "Equal" );
    else
      System.out.println( "NOT Equal" );      
  }
}

Output:
NOT Equal                   

You have seen this situation before, with two separate String objects containing the same characters:

class StringEquality
{
  public static void main ( String[] args )
  {
    String stringE = new String( "Red Delicious");
    String stringF = new String( "Red Delicious");
    
    if (arrayE==arrayF)
      System.out.println( "Equal" );
    else
      System.out.println( "NOT Equal" );      
  }
}

Output:
NOT Equal

There are two individual objects, so the object reference in stringE is not == to the object reference in stringF.

Question 22:

Confusion Alert! (review of Chapter 43)

    String stringG = "Red Delicious" ;
    String stringH = "Red Delicious" ;

    if (arrayG==arrayH)
      System.out.println( "One Literal" );
    else
      System.out.println( "NOT Equal" );         

What does the above print?

23. equals Method


Answer:

One Literal 

Recall that, as an optimization, only one object is made for string literals containing the same characters. So in the above,
both variables point to the same object. The == returns true because stringG and stringH contain identical references.

equals Method

Here is another touchy situation:

 
class ArrayEquality
{
  public static void main ( String[] args )
  {
    int[] arrayE = { 1, 2, 3, 4 };
    int[] arrayF = { 1, 2, 3, 4 };
    
    if (arrayE.equals( arrayF ) )
      System.out.println( "Equal" );
    else
      System.out.println( "NOT Equal" );      
  }
}

Output:
NOT Equal

The equals() method for arrays returns the same boolean value as does ==.

Question 23:

Are there times when you would like a method that examines two arrays (like the above two) and returns true or false depending on the elements of the array?

24. Array.equals()


Answer:

Yes. This does not happen very often, though.

Array.equals()

The class Arrays contains many static methods for manipulating arrays. Since the methods are static, you invoke them using the class name. Here is the example, this time using one of these methods:


                        
import java.util.Arrays;   // Import the package

class ArrayEquality
{
  public static void main ( String[] args )
  {
    int[] arrayE = { 1, 2, 3, 4 };
    int[] arrayF = { 1, 2, 3, 4 };
    
    if ( Arrays.equals( arrayE, arrayF ) )   // Invoke the methods thru the class name
      System.out.println( "Equal" );
    else
      System.out.println( "NOT Equal" );      
  }
}

Output:
Equal

Two arrays are equal if they are the same length, and contain the same elements in the same order. Both arrays must be of the same type.

Question 24:

A. What does this fragment output?

    int[] arrayE = { 1, 2, 3, 4, 5 }; int[] arrayF = { 1, 2, 3, 4 }; if ( Arrays.equals( arrayE, arrayF ) ) System.out.println( "Equal" ); else System.out.println( "NOT Equal" );

B. What does this fragment output?

    int[] arrayE = { 4, 3, 2, 1 }; int[] arrayF = { 1, 2, 3, 4 }; if ( Arrays.equals( arrayE, arrayF ) ) System.out.println( "Equal" ); else System.out.println( "NOT Equal" );

C. What does this fragment output?

    int[] arrayE = { 4, 3, 2, 1 }; if ( Arrays.equals( arrayE, arrayE ) ) System.out.println( "Equal" ); else System.out.println( "NOT Equal" );

25. Various equals() Methods


Answer:

A: NOT Equal

    The two arrays are different lengths.

B: NOT Equal

    The elements are not in the same order.

C: Equal

    The array is compared with itself, and found to equal.

Various equals() Methods

The method used in the above examples is this:

static boolean Array.equals( int[] a, int[] a2 )

The class Arrays has a variety of equals() methods to handle different types. But in all cases, both arrays are of the same type.

static boolean 	equals(boolean[] a, boolean[] a2)

static boolean equals(byte[] a, byte[] a2)

static boolean equals(char[] a, char[] a2)

static boolean equals(double[] a, double[] a2)

static boolean equals(float[] a, float[] a2)

static boolean equals(int[] a, int[] a2)

static boolean equals(long[] a, long[] a2)

static boolean equals(Object[] a, Object[] a2)

static boolean equals(short[] a, short[] a2)

Question 25:

Could you write your own equals() method.

26. End of the Chapter


Answer:

Yes. Usually you would use a class method. See the exercises.

End of the Chapter

That about wraps it up for this chapter. If you feel equal to it, you may wish to review the following topics.