Java.util.Arrays.deepEquals() in Java
Arrays.deepEquals() is used to check whether two arrays of single dimensional or multi-dimensional arrays are equal or not. It can compare two nested arrays (i.e. multidimensional array), irrespective of its dimension.
- Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal.
- Two possibly null elements e1 and e2 are deeply equal if any of the following conditions hold:
- e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return true
- e1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true.
- e1 == e2
- e1.equals(e2) would return true.
Note that this definition permits null elements at any depth.
- It is a method of Arrays Class
public static boolean deepEquals(Object o1, Object o2) o1 = First Array to test for Equality o2 = Second Array to test for Equality Returns true if two array are equal
Check if a1 is equal to a2 : false Check if a2 is equal to a3 : false Check if a1 is equal to a3 : true
We can even use deepEquals() to test the equality of array of Object of the user define class. Refer to the example below
We should override the equals method to define the equality of the different parameters in a user defined class.
Check if e1 is equal to e2 : true Check if e2 is equal to e3 : false Check if a1 is equal to a3 : false
Equals() vs deepEquals()
Though Arrays.equals() works correctly on an single dimensional array but it cannot check the equality of a multidimensional arrays.
While Arrays.deepEquals() work on all arrays irrespective of the dimension.
This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.