Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

true

Nested 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
true

Where 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:

2

Ignoring 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:

true

Common 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
false

Functions used in this recipe

  • Arrays.equals() — Compares the contents of two arrays element by element.

Thanks for reading!

Donate to the site — we work hard for you.