Java Arrays - deepEquals() Method
The java.util.Arrays.deepEquals() method returns true if the two specified arrays are deeply equal to one another. Unlike the equals(Object[],Object[]) method, this method is appropriate for use with nested arrays of arbitrary depth.
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.
Syntax
public static boolean deepEquals(Object[] a1, Object[] a2)
Parameters
a1 |
Specify the first array to be tested for equality. |
a2 |
Specify the second array to be tested for equality. |
Return Value
Returns true if the two arrays are equal, else returns false.
Exception
NA.
Example:
In the example below, the java.util.Arrays.deepEquals() method is used to check whether the two arrays of Objects are equal or not.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating three Object arrays Object Arr1[] = {10, 2, -3, 35, 56}; Object Arr2[] = {10, 2, -3, 35, 56}; Object Arr3[] = {5, 1, -3, 20, 25}; //check Arr1 and Arr2 for equality boolean result1 = Arrays.deepEquals(Arr1, Arr2); System.out.println("Are Arr1 and Arr2 equal?: "+ result1); //check Arr1 and Arr3 for equality boolean result2 = Arrays.deepEquals(Arr1, Arr3); System.out.println("Are Arr1 and Arr3 equal?: "+ result2); } }
The output of the above code will be:
Are Arr1 and Arr2 equal?: true Are Arr1 and Arr3 equal?: false
❮ Java.util - Arrays