VOOZH about

URL: https://www.geeksforgeeks.org/java/java-util-arrays-deepequals-java/

⇱ Arrays.deepEquals() in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Arrays.deepEquals() in Java with Examples

Last Updated : 25 Nov, 2024

Arrays.deepEquals() method comes under the Arrays class in Java. It is used to check two arrays, whether single-dimensional or multi-dimensional, are equal or not. It compares arrays element by element, even when dealing with nested arrays.

Example:

Below is a simple example that uses Arrays.deepEquals() to check if two multidimensional arrays are equal.


Output
arr1 equals with arr2: true
arr2 equals with arr3: false

Syntax of Arrays.deepEquals() method

public static boolean deepEquals(Object[] o1, Object[] o2)

Parameter:

  • o1: This is the first array to test for equality.
  • o2: This is the second array to test for equality.

Return Type: It returns true, if the two arrays are deeply equal (all elements and nested arrays are equal), otherwise it will return false.

Examples of Arrays.deepEquals() in Java

Using Arrays.deepEquals() with Multidimensional Arrays of Integers

In this example, we will check if two-dimensional arrays of integers are equal at all levels using Arrays.deepEquals().


Output
a1 is equal to a2: false
a2 is equal to a3: false
a1 is equal to a3: true


Using Arrays.deepEquals() with Arrays of User-Defined Objects

In this example, we will check if arrays of user-defined Employee objects are equal by overriding the equals() method to define the equality of different parameters in a user-defined class.


Output
e1 is equal to e2: true
e2 is equal to e3: false
e1 is equal to e3: false

Equals() vs deepEquals()

  • Arrays.equals() method works correctly on an single dimensional array, but it cannot check the equality of a multidimensional array.
  • Arrays.deepEquals() method works on all arrays irrespective of the dimension.
Comment
Article Tags: