How to compare two arrays
Short answer
Arrays.equals() compares the length and the elements in order:
void main() {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
IO.println(Arrays.equals(a, b));
}Output:
trueNested arrays
Arrays of arrays need Arrays.deepEquals():
void main() {
int[][] a = {{1, 2}, {3}};
int[][] b = {{1, 2}, {3}};
IO.println(Arrays.equals(a, b));
IO.println(Arrays.deepEquals(a, b));
}Output:
false
trueWhere they differ
Arrays.mismatch() returns the index of the first difference, or -1 if the arrays are equal:
void main() {
int[] a = {1, 2, 3, 4};
int[] b = {1, 2, 7, 4};
IO.println(Arrays.mismatch(a, b));
}Output:
2Ignoring order
Sort copies and compare them:
void main() {
int[] a = {3, 1, 2};
int[] b = {2, 3, 1};
int[] sortedA = a.clone();
int[] sortedB = b.clone();
Arrays.sort(sortedA);
Arrays.sort(sortedB);
IO.println(Arrays.equals(sortedA, sortedB));
}Output:
trueCommon mistake
Comparing arrays with == or equals(). Both check that it is the same object:
void main() {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
IO.println(a == b);
IO.println(a.equals(b));
}Output:
false
falseFunctions used in this recipe
- Arrays.equals() — Compares the contents of two arrays element by element.