Common Array Algorithms

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" );