Copying an ArrayProofer version
In this lesson, we explore how to make a duplicate copy of an array.
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.
Returns 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:
public class ArrayTasks{/** Tests whether two arrays of strings are equal.Returns true if the arrays have equal lengthsand contain equal strings in the same order. */public static boolean arraysAreEqual(String[] arrayOne, String[] arrayTwo){boolean areEqual = true; // Assume arrays are equalif (arrayOne.length == arrayTwo.length){ // Arrays have equal lengthsint index = 0;while (areEqual && (index < arrayOne.length)){if (arrayOne[index].equals(arrayTwo[index]))index++; // Pairs of entries are equal; continueelseareEqual = false; // Pairs of entries are not equal} // End while}elseareEqual = false;return areEqual;} // End arraysAreEqualpublic static void main(String[] args){String[] names = {"alpha", "beta", "gamma", "delta"};String[] tags = {"alpha", "beta", "gamma", "delta"};String[] words = {"alpha", "beta", "gamma", "delter"};if (ArrayTasks.arraysAreEqual(names, tags))System.out.println("The arrays names and tags are equal.");elseSystem.out.println("The arrays names and tags are not equal. ERROR!");if (ArrayTasks.arraysAreEqual(names, words))System.out.println("The arrays names and words are equal. ERROR!");elseSystem.out.println("The arrays names and words are not equal.");} // End main} // End ArrayTasks
Using the method Arrays.equals
The class Arrays
, which we introduced in the previous lesson, also defines a method equals
that has the same effect as the method we defined in ...