Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Arrays.equals()

Compares the contents of two arrays element by element.

Available since: Java 1.2

Syntax

static boolean equals(int[] a, int[] a2)

Parameters

ParameterTypeDescription
aint[], Object[], …The first array.
a2same array typeThe second array.

Return value

booleantrue if the lengths match and all elements are pairwise equal.

Examples

== and equals() on arrays compare references, Arrays.equals() compares contents:

void main() {
    int[] a = {1, 2, 3};
    int[] b = {1, 2, 3};
    IO.println(a == b);
    IO.println(a.equals(b));
    IO.println(Arrays.equals(a, b));
 
    int[][] x = {{1}, {2}};
    int[][] y = {{1}, {2}};
    IO.println(Arrays.equals(x, y));
    IO.println(Arrays.deepEquals(x, y));
}

Output:

false
false
true
false
true

Notes

For nested arrays Arrays.equals() compares the inner arrays as references — use deepEquals(). Order matters: {1, 2} and {2, 1} are not equal; to compare ignoring order, sort copies first.

See also

  • Arrays.toString() — Returns the contents of an array as a string like [1, 2, 3].
  • Arrays.copyOf() — Copies an array into a new one of the same or another length. copyOfRange() copies a part.
  • Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.

Related recipes

In the tutorial

  • The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.

Thanks for reading!

Donate to the site — we work hard for you.