How to Check if Two Arrays are Equal in Java

Java Array Examples


Two arrays are said to be equal if both the arrays have the same elements in the same order. You very often need to compare two arrays for equality while developing the applications.
 
Learn complete Arrays in Java at https://www.javaguides.net/2018/08/java-array-basics-guide.html.

How to Check if Two Arrays are Equal in Java Example

Here are two different methods to check the equality of two arrays.

1. Iterative Method

package net.javaguides.corejava.arrays.programs;

public class CheckTwoArrayEquals {

    public static void main(final String[] args) {
        final int[] a = {
            1,
            2,
            3
        };
        final int[] a2 = {
            1,
            2,
            3
        };
        boolean hasEqual = equalsArray(a, a2);
        System.out.println("Is two array are equal -> " + hasEqual);
    }
    private static boolean equalsArray(final int[] a, final int[] a2) {
        if (a == a2)
            return true;
        if (a == null || a2 == null)
            return false;

        final int length = a.length;
        if (a2.length != length)
            return false;

        for (int i = 0; i < length; i++)
            if (a[i] != a2[i])
                return false;

        return true;
    }
}
Output:
Is two array are equal -> true

2. Using Arrays.equals() Method

package net.javaguides.corejava.arrays.programs;

import java.util.Arrays;

public class CheckTwoArraysAreEqual {

    public static void main(final String[] args) {

        final int[] array1 = {
            1,
            2,
            3,
            4,
            5
        };
        final int[] array2 = {
            1,
            2,
            3,
            4,
            5
        };

        final boolean intCheck = Arrays.equals(array1, array2);
        System.out.println("Two Integers are Equal :: " + intCheck);
    }
}
Output:
Two Integers are Equal :: true

Reference


Comments