I have integers that are supposed to be equal (and I verify it by output). But in my if
condition Java does not see these variables to have the same value.
I have the following code:
if (pay[0]==point[0] && pay[1]==point[1]) { game.log.fine(">>>>>> the same"); } else { game.log.fine(">>>>>> different"); } game.log.fine("Compare:" + pay[0] + "," + pay[1] + " -> " + point[0] + "," + point[1]);
And it produce the following output:
FINE: >>>>>> different FINE: Compare:: 60,145 -> 60,145
Probably I have to add that point
is defined like that:
Integer[] point = new Integer[2];
and pay
us taken from the loop-constructor:
for (Integer[] pay : payoffs2exchanges.keySet())
So, these two variables both have the integer type.
To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).
Integer Equals() method in JavaThe Equals() method compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.
To check two numbers for equality in Java, we can use the Equals() method as well as the == operator. Firstly, let us set Integers. Integer val1 = new Integer(5); Integer val2 = new Integer(5); Now, to check whether they are equal or not, let us use the == operator.
For comparing two integers in Java, you can use three methods: the Comparison operator, the equals() method, and compare() method. The Comparison operator “==” is used to check equality in primitive data types, while for the objects, the equals() method is used.
Check out this article: Boxed values and equality
When comparing wrapper types such as Integer
s, Long
s or Boolean
s using ==
or !=
, you're comparing them as references, not as values.
If two variables point at different objects, they will not ==
each other, even if the objects represent the same value.
Example: Comparing different Integer objects using
==
and!=
.Integer i = new Integer(10); Integer j = new Integer(10); System.out.println(i == j); // false System.out.println(i != j); // true
The solution is to compare the values using .equals()
…
Example: Compare objects using
.equals(…)
Integer i = new Integer(10); Integer j = new Integer(10); System.out.println(i.equals(j)); // true
…or to unbox the operands explicitly.
Example: Force unboxing by casting:
Integer i = new Integer(10); Integer j = new Integer(10); System.out.println((int) i == (int) j); // true
If they were simple int
types, it would work.
For Integer
use .intValue()
or compareTo(Object other)
or equals(Object other)
in your comparison.
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