Java.util.Arrays.deepEquals() Method

Advertisements


Description

The java.util.Arrays.deepEquals(Object[] a1, Object[] a2) method returns true if the two specified arrays are deeply equal to one another.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.

Declaration

Following is the declaration for java.util.Arrays.deepEquals() method

public static boolean deepEquals(Object[] a1, Object[] a2)

Parameters

  • a1 -- This is the array to be tested for equality.

  • a2 -- This is the other array to be tested for equality.

Return Value

This method returns true if the two arrays are equal, else false.

Exception

  • NA

Example

The following example shows the usage of java.util.Arrays.deepEquals() method.

package com.tutorialspoint;

import java.util.Arrays;

public class ArrayDemo {

  public static void main(String[] args) {
   
    // initializing Object array1
    Object[] b1 = new Object[] { 'a', 'b' };

    // let us print all the values available in array2
    System.out.println("Elements of Array1 is:");
    for (Object value : b1) {
      System.out.println("Value = " + value);
    }

    // initializing Object array2
    Object[] b2 = new Object[] { 'a', 'b' };

    // let us print all the values available in array2
    System.out.println("Elements of Array2 is:");
    for (Object value : b2) {
      System.out.println("Value = " + value);
    }

    // initializing Object array3
    Object[] b3 = new Object[] { 'x', 'y' };

    // let us print all the values available in array3
    System.out.println("Elements of Array3 is:");
    for (Object value : b3) {
      System.out.println("Value = " + value);
    }

    // checking array1 and array2 for equality
    System.out.println("Array1 and Array2 are equal:" 
    + Arrays.deepEquals(b1,b2));
    
    // checking array1 and array3 for equality
    System.out.println("Array1 and Array3 are equal:" 
    + Arrays.deepEquals(b1,b3));  
  }
}  

Let us compile and run the above program, this will produce the following result:

Elements of Array1 is:
Value = a
Value = b
Elements of Array2 is:
Value = a
Value = b
Elements of Array3 is:
Value = x
Value = y
Array1 and Array2 are equal:true
Array1 and Array3 are equal:false



Advertisements
Advertisements