[java] Comparing two integer arrays in Java

I am trying to write code to compare two arrays. In the first array I have put my own digits, but the second the array takes numbers from the input file. The size of this array is determined by the first number in the file while the first array is always of size 10. The length must be the same for both arrays as well as the numbers.

My code is below:

public static void compareArrays(int[] array1, int[] array2) {
    boolean b = false;
    for (int i = 0; i < array2.length; i++) {

        for (int a = 0; a < array1.length; a++) {

            if (array2[i] == array1[a]) {
                b = true;
                System.out.println("true");
            } else {
                b = false;
                System.out.println("False");
                break;
            }
        }
    }       
}

This question is related to java arrays compare

The answer is


The length of the arrays must be the same and the numbers just be the same throughout(1st number in arrays must be the sasme and so on)

Based on this comment, then you already have your algorithm:

  1. Check if both arrays have the same length:

    array1.length == array2.length

  2. The numbers must be the same in the same position:

    array1[x] == array2[x]

Knowing this, you can create your code like this (this is not Java code, it's an algorithm):

function compareArrays(int[] array1, int[] array2) {

    if (array1 == null) return false
    if (array2 == null) return false

    if array1.length != array2.length then return false

    for i <- 0 to array1.length - 1
        if array1[i] != array2[i] return false

    return true
}

Note: your function should return a boolean, not being a void, then recover the return value in another variable and use it to print the message "true" or "false":

public static void main(String[] args) {
    int[] array1;
    int[] array2;
    //initialize the arrays...
    //fill the arrays with items...
    //call the compare function
    boolean arrayEquality = compareArrays(array1, array2);
    if (arrayEquality) {
        System.out.println("arrays are equals");
    } else {
        System.out.println("arrays are not equals");
    }
}

If you know the arrays are of the same size it is provably faster to sort then compare

Arrays.sort(array1)
Arrays.sort(array2)
return Arrays.equals(array1, array2)

If you do not want to change the order of the data in the arrays then do a System.arraycopy first.


Even though there is something easy like .equals, I'd like to point out TWO mistakes you made in your code. The first: when you go through the arrays, you say b is true or false. Then you start again to check, because of the for-loop. But each time you are giving b a value. So, no matter what happens, the value b gets set to is always the value of the LAST for-loop. Next time, set boolean b = true, if equal = true, do nothing, if equal = false, b=false.

Secondly, you are now checking each value in array1 with each value in array2. If I understand correctly, you only need to check the values at the same location in the array, meaning you should have deleted the second for-loop and check like this: if (array2[i] == array1[i]). Then your code should function as well.

Your code would work like this:

public static void compareArrays(int[] array1, int[] array2) {
    boolean b = true;
    for (int i = 0; i < array2.length; i++) {
        if (array2[i] == array1[i]) {
            System.out.println("true");
        } else {
            b = false;
            System.out.println("False");
        }
    } 
    return b;

}

But as said by other, easier would be: Arrays.equals(ary1,ary2);


use
Arrays.equals(ary1,ary2); // returns boolean value

EDIT
you can use Arrays.deepEquals(ary1,ary2) to compare 2D arrays as well

also check this link for comparision comparision between Arrays.equls(ar1,ar2) and Arrays.deepEquals(ar1,ar2)

Java Arrays.equals() returns false for two dimensional arrays

EDIT 2
if you dont want to use these library methods then you can easily implement your method like this:

public static boolean ArrayCompare(int[] a, int[] a2) {
    if (a==a2)   // checks for same array reference
        return true;
    if (a==null || a2==null)  // checks for null arrays
        return false;

    int length = a.length;
    if (a2.length != length)  // arrays should be of equal length
        return false;

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

    return true;
}

For the sake of completeness, you should have a method which can check all arrays:

    public static <E> boolean compareArrays(E[] array1, E[] array2) {
      boolean b = true;
      for (int i = 0; i < array2.length; i++) {
        if (array2[i].equals(array1[i]) ) {// For String Compare
           System.out.println("true");
        } else {
           b = false;
           System.out.println("False");
        }
      } 
      return b;
    }

You can check array equality with the Apache Commons ArrayUtils#isEquals() method.


Here my approach,it may be useful to others.

public static void compareArrays(int[] array1, int[] array2) {
    if (array1.length != array2.length)
    {
           System.out.println("Not Equal");
    }
    else
    {
        int temp = 0;
        for (int i = 0; i < array2.length; i++) {  //Take any one of the array size
            temp^ = array1[i] ^ array2[i];   //with help of xor operator to find two array are equal or not                 
        }
        if( temp == 0 )
        {
             System.out.println("Equal");
        }
        else{
             System.out.println("Not Equal");
        }
    }
}

None of the existing answers involve using a comparator, and therefore cannot be used in binary trees or for sorting. So I'm just gonna leave this here:

public static int compareIntArrays(int[] a, int[] b) {
    if (a == null) {
        return b == null ? 0 : -1;
    }
    if (b == null) {
        return 1;
    }
    int cmp = a.length - b.length;
    if (cmp != 0) {
        return cmp;
    }
    for (int i = 0; i < a.length; i++) {
        cmp = Integer.compare(a[i], b[i]);
        if (cmp != 0) {
            return cmp;
        }
    }
    return 0;
}

From what I see you just try to see if they are equal, if this is true, just go with something like this:

boolean areEqual = Arrays.equals(arr1, arr2);

This is the standard way of doing it.

Please note that the arrays must be also sorted to be considered equal, from the JavaDoc:

Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order.

Sorry for missing that.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to compare

Checking for duplicate strings in JavaScript array How to compare two files in Notepad++ v6.6.8 How to compare LocalDate instances Java 8 Comparing the contents of two files in Sublime Text comparing elements of the same array in java How to compare two dates along with time in java bash string compare to multiple correct values Query comparing dates in SQL How to compare two java objects Comparing two integer arrays in Java