Completion requirements
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.
24. Array.equals()
Answer:
Yes. This does not happen very often, though.
Array.equals()
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" );