29

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;
            }
        }
    }       
}
informatik01
  • 16,038
  • 10
  • 74
  • 104
user2052514
  • 467
  • 1
  • 4
  • 9
  • 7
    And what problem do you have? – Rich Feb 15 '13 at 14:59
  • 2
    @Rich it looks like OP isn't comparing the arrays at all. Just read the code – Luiggi Mendoza Feb 15 '13 at 15:00
  • What's the question? Does it not work? – thegrinner Feb 15 '13 at 15:00
  • it dosn't work at all when the two numbers are the same it still returns false – user2052514 Feb 15 '13 at 15:01
  • 3
    First you should define to us how will you determine if two array are equals for your exercise: same array length and same items but not in the same order, different array lengths but same items (accept repeated items and not in the same order), both arrays with same length and same items in the same place? – Luiggi Mendoza Feb 15 '13 at 15:02
  • 1
    This is nice code to create a random boolean value, though. What do you mean with `the two numbers` ? – Ingo Feb 15 '13 at 15:02
  • 4
    I don't know if I'm right, but I think this looks like an exercise to learn Java and algorithms. Since OP's in learning phase, why would people just go the *easy* way and say *use the `Arrays#someFancyFunctionThatWontHelpYouToLearn`? Instead, we should focus on helping OP to 1. Understand the problem, and 2. Reach his/her own answer. Giving a fish to a fisherman will never help him to learn how to fish. – Luiggi Mendoza Feb 15 '13 at 15:06
  • It is not clear, should the Method return `true` even if the 2nd Array is larger than the 1st. – oliholz Feb 15 '13 at 15:07
  • @oliholz that's what I'm asking in [my comment](http://stackoverflow.com/questions/14897366/comparing-two-array-in-java#comment20893567_14897366) – Luiggi Mendoza Feb 15 '13 at 15:08
  • are you checking if array2 contains array1? (are you checking if one is a subset of the other?) – andre Feb 15 '13 at 15:08
  • 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) – user2052514 Feb 15 '13 at 15:09
  • To OP: 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`. – Joetjah Feb 15 '13 at 15:10
  • 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. – Joetjah Feb 15 '13 at 15:11
  • @Joetjah you should write an answer instead of lots of comments that provide an answer :) – Luiggi Mendoza Feb 15 '13 at 15:12
  • @Luiggi Mendoza your right, i received your comment after i committed mine – oliholz Feb 15 '13 at 15:14
  • I remade my answer to reflect it all – Joetjah Feb 15 '13 at 15:17

10 Answers10

73

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.

informatik01
  • 16,038
  • 10
  • 74
  • 104
comanitza
  • 1,103
  • 2
  • 10
  • 17
  • 15
    Arrays.sort() doesn't return sorted array – Sergey Grinev Aug 23 '13 at 11:45
  • 15
    Sorting the arrays is completely wrong. Imagine two arrays `a={ 0, 1 }` and `b={ 1, 0 }`. They are totally not equal, but sorting and comparing them would say it is. What you are doing is finding, if there are the same elements in the array, but that is a different thing. – Petr Dec 03 '13 at 13:49
  • 4
    I think this answer was right until they added the sort, and that's how this got the original upvotes. – Paul Jan 08 '15 at 14:47
35

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;
}
Community
  • 1
  • 1
exexzian
  • 7,782
  • 6
  • 41
  • 52
  • Read my comment in OP's question. By the way, it has 2 upvotes. – Luiggi Mendoza Feb 15 '13 at 15:10
  • I am not the downvoret but you all got -1 probably for spoon-feeding OP since he/she is in learning phase answer should be more about algorithm not correct method. – Pshemo Feb 15 '13 at 15:11
  • 6
    I was not spoon feeding was just making him aware of these library methods - and I haven`t seen till now - getting an answer downvoted for soemething like this purpose (where answer is not at wrong) - this way you will make OP and future referrers more confused – exexzian Feb 15 '13 at 15:13
  • @user2052514 check my updated answer - have included method implementation as well along with library methods – exexzian Feb 15 '13 at 15:30
19
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);
    }
slawter
  • 525
  • 4
  • 14
  • 5
    It's better to print false and break the loop at the first instance of two elements not being equal. Similarly, returning false if the method has a boolean type. It's pointless and resource inefficient to iterate through 1000 elements if the first one is different. I'd also argue returning a boolean and printing based on that is better. That way the method can be used even when you want to silently check for equality. While this answer may have served the OP, I think exexzian's answer is more complete. – Reti43 Nov 18 '15 at 14:57
7

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.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • [`sort()`](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(int[])) uses a [quicksort](http://iaroslavski.narod.ru/quicksort/DualPivotQuicksort.pdf) with an average of `2*n*ln(n)` comparisons, wherease `equals()` just requires `n` comparisons in the *worst* case. Not to mention actually swapping elements. This is much slower, not faster, and even an optimal radix sort would be slower. – Matthew Read Jul 24 '15 at 17:30
  • @MatthewRead it uses TimSort. Comparing all pairs of elements is `O(n^2)`. This checks whether both arrays contain the _same elements_. You can only check whether the arrays contain the same elements in _the same order_ in `O(n)`. It depends on your concept of equality but your suggestion and this answer are **not equivalent**. – Boris the Spider Jul 24 '15 at 17:33
2

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

tstorms
  • 4,941
  • 1
  • 25
  • 47
  • 4
    I don't agree with the downvote. This does anwser his question and he can always dive in the source code to see how it works... – tstorms Feb 15 '13 at 15:11
  • yeah why to downvote - there is nothing wrong with this answer as well - even if OP is learning - even then there is nothing wrong in introducing him with these libraries and methods which are available – exexzian Feb 15 '13 at 15:15
  • @sansix so your first Java programming class was about handling collections? No? Then start with the basics. – Luiggi Mendoza Feb 15 '13 at 15:22
  • 1
    @LuiggiMendoza seems your Java programming till now is like approahing for same lame procedural steps :P - God Knows why these libraries are available when guys like you are available :P – exexzian Feb 15 '13 at 15:24
  • @sansix what part of *learning phase* didn't you understand? Would you give a lamborghini to a guy who's taking his first driving lesson? – Luiggi Mendoza Feb 15 '13 at 15:26
  • 1
    @LuiggiMendoza why not? if his father is rich enough to afford many of them - in the same way if there are rich set of libraries available why not use them? if one has to learn he can easily learn from those things as well - Java is Open Source - and code is easily available – exexzian Feb 15 '13 at 15:35
2

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;
}
etherous
  • 709
  • 4
  • 10
  • `int cmp = a.length - b.length;` can return any int (but 0), not necessarily 1 or -1 – c0der Nov 23 '16 at 16:55
  • @c0der That's true. When it comes to comparators in Java, any negative int can be returned to indicate "less-than", and any positive int indicates "greater-than". It need not be one of {-1,0,1} – etherous Dec 06 '16 at 20:52
  • Reading https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html#compare(T,%20T) I see: " defined to return one of -1, 0, or 1 " – c0der Dec 08 '16 at 07:53
1

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

Joetjah
  • 6,292
  • 8
  • 55
  • 90
  • PS. I edited an other answer by someone else into my text. I'm screwing up :( – Joetjah Feb 15 '13 at 15:16
  • I tried this code and it work ok for the array that dosn't match but when the arrays are the same I get true and false printed. – user2052514 Feb 15 '13 at 15:17
  • I'm sorry, I totally missed your `break`-statement. That is actually pretty correct! That means your code has only 1 flaw, and that's the double for-loop. – Joetjah Feb 15 '13 at 15:20
  • @Joetjah the arrays should be in the same order for Arrays.equals() to work, so you need so do something like Arrays.equals(Arrays.sort(arr1), Arrays.sort(arr2)); – comanitza Feb 15 '13 at 16:16
  • That's true. I assumed in this case the arrays are the same or if he needed to check them if they are sorted the same way. – Joetjah Feb 15 '13 at 19:25
1

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");
    }
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • if you think this was your best answer for OP to make him learn things right way - then you better check for few more conditions- check my edit – exexzian Feb 15 '13 at 15:26
  • for a robust util method, add `null`-check for `array1` and `array2` – oliholz Feb 15 '13 at 15:27
0

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");
        }
    }
}
Nayagam
  • 1,767
  • 18
  • 12
  • I wrote the same function code by chance to compare 2 arrays of ints, but if `array1 = [-1, -2, 3]; array2 = [-1, 2, -1];` and the function's result would be `true` – Gale Yao Jan 18 '23 at 05:21
-2

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;
    }
BERGUIGA Mohamed Amine
  • 6,094
  • 3
  • 40
  • 38