Java.util.Arrays.deepEquals() in Java
Last Updated :
07 Aug, 2017
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.
Syntax:
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
import java.util.Arrays;
public class GFG {
public static void main(String[] args)
{
int a1[][] = { { 10 , 20 },
{ 40 , 50 },
{ 60 , 70 } };
int a2[][] = { { 30 , 20 },
{ 10 , 0 },
{ 60 , 80 } };
int a3[][] = { { 10 , 20 },
{ 40 , 50 },
{ 60 , 70 } };
System.out.println( "Check if a1 is equal to a2 : "
+ Arrays.deepEquals(a1, a2));
System.out.println( "Check if a2 is equal to a3 : "
+ Arrays.deepEquals(a2, a3));
System.out.println( "Check if a1 is equal to a3 : "
+ Arrays.deepEquals(a1, a3));
}
}
|
Output:
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.
Output:
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.
Reference :
https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#deepEquals-java.lang.Object:A-java.lang.Object:A-
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...