Comparing two arrays for equality

In this post under Java, I will show with example how to check whether two arrays are equal or not.

The class Arrays under java.util package has “equals” static method which takes two arrays as arguments and compare their contents to check whether they are same.

Below is the code showing an example

Main


1  package collections;
2  
3  import java.util.Arrays;
4  
5  public class ArraysDemo2 {
6      public static void main(String[] args) {
7          int[] array1 = {1, 2, 3, 4};
8          int[] array2 = {1, 3, 2, 4};
9          int[] array3 = {1, 2, 3, 4};
10         
11         System.out.println("array1 equals array2: " + Arrays.equals(array1, array2));
12         System.out.println("array1 equals array3: " + Arrays.equals(array1, array3));
13     }
14 }

Below is the output

Output

array1 equals array2: false
array1 equals array3: true

Leave a Reply