Course contentsShow
← Java
Lesson 271 of 2,8706. ArraysFree lesson

Arrays.equals and Arrays.deepEquals

Comparing arrays for equality by content, including nested arrays with deepEquals.

Arrays.equals and Arrays.deepEquals

What You'll Learn

You'll learn how to properly compare arrays by their content using Arrays.equals() for simple arrays and Arrays.deepEquals() for nested arrays.


Why == Doesn't Work for Array Content

When you compare arrays with ==, Java only checks if both variables point to the same array object in memory, not whether their contents match. It's like checking if two shopping lists are the exact same piece of paper, rather than checking if they contain the same items.

int[] list1 = {1, 2, 3};
int[] list2 = {1, 2, 3};
System.out.println(list1 == list2);  // false — different objects!

Arrays.equals(): Content-Based Comparison

Arrays.equals() compares two arrays element-by-element to see if they contain the same values in the same order:

int[] list1 = {1, 2, 3};
int[] list2 = {1, 2, 3};
System.out.println(Arrays.equals(list1, list2));  // true — same content!

This works for arrays of primitives and reference types. For reference types, it uses the equals() method of each element.

Arrays.deepEquals(): For Nested Arrays

If your array contains other arrays (multidimensional or jagged arrays), Arrays.equals() won't look inside the nested arrays. Use Arrays.deepEquals() instead:

int[][] matrix1 = {{1, 2}, {3, 4}};
int[][] matrix2 = {{1, 2}, {3, 4}};

System.out.println(Arrays.equals(matrix1, matrix2));      // false!
System.out.println(Arrays.deepEquals(matrix1, matrix2));  // true!

deepEquals() recursively compares nested arrays at any depth, ensuring the entire structure matches.


Key Takeaway: Use Arrays.equals() to compare arrays by content, and Arrays.deepEquals() when comparing multidimensional or nested arrays. Never rely on == for content comparison.