What is the difference between using `equals` and `Arrays.equals` when comparing arrays in Java, and how do they behave differently?

I’m trying to understand how array equals comparisons work in Java. Given two arrays:

Object[] array1, array2;
array1.equals(array2);
Arrays.equals(array1, array2);

What exactly is the difference in how these two statements compare the arrays? How should I choose which one to use when I want to check if two arrays have the same contents?

When you call array1.equals(array2); you’re using the default equals() method from Object. This does not compare the contents of the arrays — it simply checks if both variables refer to the same memory location.

Think of it like this: it’s asking, “Are these two arrays literally the same object?”

So even if all elements are identical, array1.equals(array2) will return false unless array1 and array2 are pointing to the exact same object.

Use this when you only care if both references are the same array instance.

Here’s the preferred method when you want to check if two arrays contain the same elements in the same order:

Arrays.equals(array1, array2);

This method iterates through both arrays and checks each element using their equals() method.

:heavy_check_mark: Works perfectly for:

  • One-dimensional arrays (like int[], String[], or Object[])

  • Content-based comparison

:no_entry_sign: But: It does not work correctly for multi-dimensional arrays like String[][].

If you have multi-dimensional arrays (e.g., Object[][]), you’ll want to use:

Arrays.deepEquals(array1, array2);

Why? Because Arrays.equals() will just compare nested array references not the contents inside them. deepEquals() goes the extra mile to recursively compare elements in nested arrays.

Use this when you’re dealing with nested arrays. You want a deep comparison of all levels