Comparing two integer arrays in Java Comparing two integer arrays in Java arrays arrays

Comparing two integer arrays in Java


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.


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;}


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