Copying an ArrayProofer version
In this lesson, we explore how to make a duplicate copy of an array.
We'll cover the following...
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:
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 the previous segment. Thus, given the arrays names and tags, the expression Arrays.equals(names, tags)
returns true.
📝 Note: Testing arrays for equality
To be equal, two arrays must contain the same entries in the same order. That ...