How to Compare Two Arrays in Java - String, Integer Array Example

Our task is to compare two arrays in Java and see if they are equal to each other or not. Of-course we can't compare an String array to an int array, which means two arrays are said to be equal if they are of same type, has same length, contains same elements and in same order. Now, you can write your own method for checking array equality or take advantage of Java's rich Collection API. Similar to what we have seen while printing array values in Java, java.util.Arrays class provides convenient methods for comparing array values. They take care of all four condition, I have mentioned above. In fact, Arrays class also provide deepEquals() method to compare two-dimensional array in Java. By the way it's not restricted to just two-dimensional and also valid for any multi-dimensional array.

In this article, we will see examples of comparing two String array, two Integer array and two multi dimensional array to learn how to use equals() and deepEquals() methods of java.util.Arrays class. Also difference between equals() and deepEquals() is a good Java interview question, and asked into of couple of fresher and mid level interviews.




Comparing two Integer Array in Java

In order to compare two integer array in Java, all you need to do is import java.util.Arrays class. This class contains two methods related to array comparison equals() and deepEquals(), both are overloaded to accept all primitive arrays and one version for accepting Object array. We need to use the equals(int[], int[]) method to compare our integer arrays, as shown below. As you can see, I have defined 3 integer arrays, each of same size but different numbers. int[] even and meEvenToo are equal to each other because they are of same type, same length, and contains same number in same order. While, int[] odd is not equal to int[] even, because though they are of same type and length, their individual content is different. As expected equals(int[], int[]) method of Arrays class produced correct result.

int[] even = {2, 4, 6};
int[] meEvenToo = {2, 4, 6};
int[] odd = {3, 5, 7};
boolean result = Arrays.equals(even, meEvenToo);
System.out.printf("Comparing two int arrays %s and %s, are they Equal? %s %n ",
                Arrays.toString(even), Arrays.toString(meEvenToo), result);

result = Arrays.equals(even, odd);
System.out.printf("Comparing even and odd int arrays %s and %s, are they Equal? %s %n",
                Arrays.toString(even), Arrays.toString(odd), result);

Output:
Comparing two int arrays [2, 4, 6] and [2, 4, 6], are they Equal? true
Comparing even and odd int arrays [2, 4, 6] and [3, 5, 7], are they Equal? false


Comparing two String array in Java

How to compare Array in Java with Example
As I said in previous section that java.util.Arrays class has overloaded equals() and deepEquals() to accept object[]. Since arrays are co-variant, you can pass String[] to a method which accepts an Object[], which is used to compare String array in Java. In this example we have three string array of length 2, out of three String[] numbers and digits are equal, because they also contain same values at similar index, but String[] numbers and numeric are unequal because there values at respective index is different. Remember, equality logic of individual object is handled by equals() method of that class itself, which means even string comparison inside array is case sensitive.

String[] numbers = {"one", "two"};
String[] numeric = {"three", "two"};
String[] digits = {"one", "two"};

result = Arrays.equals(numbers, numeric);
System.out.printf("Comparing two String arrays %s and %s, are they Equal? %s %n ",
                Arrays.toString(numbers), Arrays.toString(numeric), result);

result = Arrays.equals(numbers, digits);
System.out.printf("Comparing two unequal String arrays %s and %s, are they same? %s %n",
                Arrays.toString(numbers), Arrays.toString(digits), result);

Output :
Comparing two String arrays [one, two] and [three, two], are they Equal? false
Comparing two unequal String arrays [one, two] and [one, two], are they same? true


Comparing two multidimensional array in Java

Comparing multi-dimensional array is slightly different then comparing one dimensional arrays, because instead of Arrays.equals(), you need to use Arrays.deepEquals(). Tricky part is that, compiler will not catch your array of passing multi-dimensional array to Arrays.equals() method, which also doesn't throw any exception and simply return false. This can lead to subtle bugs, sometime very hard to catch. So, pay special care while comparing multi-dimensional array and ensure that you have used deepEquals() and not equals(). Here is an example of comparing two dimensional array in Java.

char[][] abcd = {{'A', 'B'}, {'C', 'D'}};
char[][] efgh = {{'E', 'F'}, {'G', 'H'}};
char[][] ABCD = {{'A', 'B'}, {'C', 'D'}};

result = Arrays.equals(abcd, efgh);
System.out.printf("Comparing two dimensional arrays %s and %s in Java, Equal? %s %n ",
                Arrays.deepToString(abcd), Arrays.deepToString(efgh), result);

result = Arrays.deepEquals(abcd, ABCD); // using equals() will return false
System.out.printf("Comparing unequal two dimensional char arrays %s and %s in Java, are they same? %s %n",
                Arrays.deepToString(abcd), Arrays.deepToString(ABCD), result);

Output:
Comparing two dimensional arrays [[A, B], [C, D]] and [[E, F], [G, H]] in Java, Equal? false
Comparing unequal two dimensional char arrays [[A, B], [C, D]] and [[A, B], [C, D]] in Java, are they same? true

Source code of Java Program for Comparing two arrays

Here is the complete code sample of how to compare two arrays in Java. You don't need any third-party library, just JDK. If  you are using any IDE like Eclipse or Netbeans, then just copy paste this code in a Java source file, whose name matches with public class name and run it. Alternatively you can also run this from command prompt.

import java.util.Arrays;

/**
 * Java Program to print arrays in Java. We will learn how to print String, int,
 * byte and two dimensional arrays in Java by using toString() and
 * deepToString() method of Arrays class.
 *
 * @author javinpaul
 */
public class ArrayComparisionDemo {

    public static void main(String args[]) {

        // Example 1 : Comparing two int arrays in Java
        int[] even = {2, 4, 6};
        int[] meEvenToo = {2, 4, 6};
        int[] odd = {3, 5, 7};

        boolean result = Arrays.equals(even, meEvenToo);
        System.out.printf("Comparing two int arrays %s and %s, are they Equal? %s %n ",
                Arrays.toString(even), Arrays.toString(meEvenToo), result);

        result = Arrays.equals(even, odd);
        System.out.printf("Comparing even and odd int arrays %s and %s, are they Equal? %s %n",
                Arrays.toString(even), Arrays.toString(odd), result);


        // Example 2 : Comparing two String array in Java
        String[] numbers = {"one", "two"};
        String[] numeric = {"three", "two"};
        String[] digits = {"one", "two"};

        result = Arrays.equals(numbers, numeric);
        System.out.printf("Comparing two String arrays %s and %s, are they Equal? %s %n ",
                Arrays.toString(numbers), Arrays.toString(numeric), result);

        result = Arrays.equals(numbers, digits);
        System.out.printf("Comparing two unequal String arrays %s and %s, are they same? %s %n",
                Arrays.toString(numbers), Arrays.toString(digits), result);


        // Example 3 : Comparing two multi-dimensional array in Java
        char[][] abcd = {{'A', 'B'}, {'C', 'D'}};
        char[][] efgh = {{'E', 'F'}, {'G', 'H'}};
        char[][] ABCD = {{'A', 'B'}, {'C', 'D'}};

        result = Arrays.equals(abcd, efgh);
        System.out.printf("Comparing two dimensional arrays %s and %s in Java, Equal? %s %n",
                Arrays.deepToString(abcd), Arrays.deepToString(efgh), result);

        result = Arrays.deepEquals(abcd, ABCD); // using equals() will return false
        System.out.printf("Comparing unequal two dimensional char arrays %s and %s in Java, are they same? %s %n",
                Arrays.deepToString(abcd), Arrays.deepToString(ABCD), result);
    }
}

Output:
Comparing two int arrays [2, 4, 6] and [2, 4, 6], are they Equal? true
Comparing even and odd int arrays [2, 4, 6] and [3, 5, 7], are they Equal? false
Comparing two String arrays [one, two] and [three, two], are they Equal? false
Comparing two unequal String arrays [one, two] and [one, two], are they same? true
Comparing two dimensional arrays [[A, B], [C, D]] and [[E, F], [G, H]] in Java, Equal? false
Comparing unequal two dimensional char arrays [[A, B], [C, D]] and [[A, B], [C, D]] in Java, are they same? true

That's all about how to compare two arrays in Java. By using equals() and deepEquals() method of java.util.Arrays class, you can easily compare any arbitrary array in Java. We have seen examples of comparing String arrays, int arrays and multi-dimensional arrays in Java programs. One thing to note is that, you must use deepEquals() method to compare two dimensional arrays in Java, using equals() in such case does not produce correct result. Do you know any other clever way to compare array in Java?


3 comments:

  1. good explanation

    ReplyDelete
  2. Thanks for the clear explanation!

    ReplyDelete
  3. hi i want a java program for,taking input like 0101000111001000110000 and print the output if u find 000 in our input print 0 and same find 100 print 1

    eg; in given input 0101000111001000110000 the o/p----10110

    ReplyDelete