Note. Array Equality
[comp1110-73]
Note. Array Equality
[comp1110-73]We've seen earlier that String Equality requires special attention compared to the more common equality operator ==.
This is because the operator == expresses sameness, either of a numerical value, or of something larger within computer memory.
Sameness implies equality, but not necessarily the other way around.
We will look at the technical reasons for this later in the course.
Similar to Strings, Arrays are also larger things in computer memory. But in contrast to Strings, the contents of arrays can change. What that means is that if your idea of equality is that two arrays contain equal values in the same order, then that may be true at one point in your program, and false at a different point, as the contents of one or both of the arrays may change in the meantime. This means that the identity of each array matters a lot more than it does for Strings.
For that reason, a.equals(b) on arrays is the same as a == b.
However, the Java Standard Libraries contain a number of standard functions dealing with arrays, among them a suitable equality function.
To use it, you need to add an import declaration for java.util.Arrays to the top of your file.
You can then use the expression Arrays.equals(a,b) to compare two arrays for equality based on the equality of their elements.