How to Check If Two Arrays are Equal or Not in Java



To check if two arrays are equal is to compare their contents in order to determine whether they have the same elements in the same order. Java supports the use of built-in methods, such as Arrays.equals() for one-dimensional arrays and Arrays.deepEquals() for multi-dimensional arrays, making this a relatively easy operation to perform. The following are the ways to check if two arrays are equal or not

  • Using Arrays.equals() Method

  • Using == Operator

  • Using Arrays.deepEquals() Method (for multi-dimensional arrays)

Using Arrays.equals() Method

The Arrays.equals() method compares the actual contents of two arrays. It returns true if both arrays are equal, meaning they have the same elements in the same order.

Syntax

The following is the syntax for java.util.Arrays.equals() method

public static boolean equals(Object[] a, Object[] a2)

Example

Following example shows how to use equals () method of Arrays to check if two arrays are equal or not.

import java.util.Arrays;

public class Main {
   public static void main(String[] args) throws Exception {
      int[] ary = {1,2,3,4,5,6};
      int[] ary1 = {1,2,3,4,5,6};
      int[] ary2 = {1,2,3,4};
      System.out.println("Is array 1 equal to array 2?? " +Arrays.equals(ary, ary1));
      System.out.println("Is array 1 equal to array 3?? " +Arrays.equals(ary, ary2));
   }
}

Output

Is array 1 equal to array 2?? true
Is array 1 equal to array 3?? false

Using == Operator

The == operator checks if two array references point to the same object in memory, not whether their contents are the same. This method is not suitable for comparing the actual contents of arrays.

Example

Following is an example of comparing arrays

import java.util.Arrays;

public class HelloWorld {
   public static void main (String[] args) {
      int arr1[] = {1, 2, 3};
      int arr2[] = {1, 2, 3};
      if (Arrays.equals(arr1, arr2)) System.out.println("Same");
      else System.out.println("Not same");
   }
}

Output

Same   

Using Arrays.deepEquals() Method (for multi-dimensional arrays)

For comparing multi-dimensional arrays, Arrays.deepEquals() is often used as it compares arrays recursively, comparing their contents deeply.

Syntax

The following is the syntax for java.util.Arrays.deepEquals() method

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

Example

Following is another example of comparing arrays

public class HelloWorld {
   public static void main (String[] args) {
      int arr1[] = {1, 2, 3};
      int arr2[] = {1, 2, 3};
      
      if (arr1 == arr2) System.out.println("Same");
      else System.out.println("Not same");
   }
}

Output

Not same      
java_arrays.htm
Advertisements