Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare int arrays in Java? [duplicate]

Tags:

java

arrays

When I am trying to compare two int array, even though they are exactly the same, the code inside if (one == two) still doesn't get executed. Why is this?

Object[] one = {1,2,3,4,5,6,7,8,9};
Object[] two = {1,2,3,4,5,6,7,8,9};

if (one == two){
    System.out.println("equal");
} else {
    System.out.println("not equal");
}
like image 569
Thor Avatar asked Dec 14 '22 07:12

Thor


1 Answers

A few things to note here:

  • == compares the references, not the values . . . that is, you are asking whether these two arrays are the same exact instance, not whether they contain the same values.
  • The fact that you are using == means you may not know about the equals() method on Object. This is not the method you'll need to solve this current problem, but just be aware that in general, when you compare the values of two objects, you should be using obj1.equals(obj2), not obj1 == obj2. Now == does work with primitives like int (e.g. plain old x == 3 and so on), so maybe that's why you were using it, but I just wanted to make sure you were aware of equals() vs. ==.
  • In the old old days (pre-1998), you would have to compare each element pair of the two arrays. Nowadays, you can just use that static Arrays.equals() method on the java.util.Arrays class. This method is overloaded for all the primitive types (using == under the hood for each element pair) and for Object (where it will most definitely use equals() for each pair.)
like image 73
sparc_spread Avatar answered Dec 16 '22 20:12

sparc_spread