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");
}
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. ==
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. ==
.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.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With