Array Equality

We now examine the meaning of equality between two arrays and learn how to test for it.

The meaning of array equality

If we have two distinct arrays, what does it mean to say that the arrays are equal? Arrays are equal when their corresponding entries are equal. For example, the following two arrays are equal:

String[] names = {"alpha", "beta", "gamma", "delta"};
String[] tags = {"alpha", "beta", "gamma", "delta"};

The arrays have the same length, and the strings in corresponding elements are equal in value. That is, names[index] equals tags[index] as index ranges in value from 0 to 3. Since the arrays contain strings, we could test the equality of these entries by evaluating the Boolean expression names[index].equals(tags[index]) for all values of index. We will do this in the next segment.

Testing for array equality

We can write our own method that checks whether two arrays are equal, or we can use a method that Java supplies. We will look at both approaches.

Using your own method

Suppose that we define a class of static methods to perform various operations on arrays. Among these methods, let’s define the following static method that tests whether two given arrays of strings are equal:

/** Tests whether two arrays of strings are equal.
    @return true if the arrays have equal lengths 
    and contain equal strings in the same order. */
public static boolean arraysAreEqual(String[] arrayOne, String[] arrayTwo)

The following program defines and tests this method:

Get hands-on with 1200+ tech skills courses.