Comparing Two Arrays in Java

 Comparing Two Arrays in Java

1. Using Arrays.equals() Method

The Arrays.equals() method is the most straightforward way to compare two arrays. It checks if both arrays are of the same length and all corresponding pairs of elements in the two arrays are equal.

import java.util.Arrays;

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

2. Using Arrays.deepEquals() Method

When dealing with multidimensional arrays, Arrays.deepEquals() is used. It checks both arrays deeply that is, it checks both arrays’ dimensions and all corresponding pairs.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int arr1[][] = {{1, 2, 3}, {4, 5}};
        int arr2[][] = {{1, 2, 3}, {4, 5}};
        boolean isEqual = Arrays.deepEquals(arr1, arr2);
        System.out.println(isEqual ? "Same" : "Not same");
    }
}

3. Using Arrays.mismatch() Method

The Arrays.mismatch() method returns the index of the first mismatch between the two arrays, or -1 if no mismatch is found. It’s a useful method when you want to know the exact position where the arrays differ.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int arr1[] = {1, 2, 3, 4};
        int arr2[] = {1, 2, 3, 5};
        int mismatchIndex = Arrays.mismatch(arr1, arr2);
        System.out.println(mismatchIndex);
    }
}

4. Using a Loop to Compare Arrays

If you want to avoid using built-in methods, you can compare two arrays using a simple loop. This method involves iterating over each element in the arrays and comparing them.

public class Main {
    public static void main(String[] args) {
        int arr1[] = {1, 2, 3};
        int arr2[] = {1, 2, 3};
        boolean isEqual = true;

        if (arr1.length == arr2.length) {
            for (int i = 0; i < arr1.length; i++) {
                if (arr1[i] != arr2[i]) {
                    isEqual = false;
                    break;
                }
            }
        } else {
            isEqual = false;
        }

        System.out.println(isEqual ? "Same" : "Not same");
    }
}

Post a Comment

Previous Post Next Post