为什么 Java 看不到整数相等? [英] Why Java does not see that Integers are equal?
问题描述
我有应该相等的整数(我通过输出验证它).但是在我的 if
条件下,Java 没有看到这些变量具有相同的值.
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.
我有以下代码:
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]);
它产生以下输出:
FINE: >>>>>> different
FINE: Compare:: 60,145 -> 60,145
可能我必须补充一点,point
是这样定义的:
Probably I have to add that point
is defined like that:
Integer[] point = new Integer[2];
和 pay
我们从循环构造函数中取出:
and pay
us taken from the loop-constructor:
for (Integer[] pay : payoffs2exchanges.keySet())
所以,这两个变量都是整数类型.
So, these two variables both have the integer type.
推荐答案
查看这篇文章:盒装值和平等
当使用 ==
或 ==
s、Long
s 或 Boolean
s 比较包装器类型时code>!=,您将将它们作为参考进行比较,而不是作为值进行比较.
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.
示例: 使用 ==
和 !=
比较不同的 Integer 对象.
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
解决方案是使用 .equals()
...
The solution is to compare the values using .equals()
…
示例: 使用 .equals(…)
Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println(i.equals(j)); // true
...或显式拆箱操作数.
…or to unbox the operands explicitly.
示例:强制取消装箱:
Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println((int) i == (int) j); // true
参考资料/进一步阅读
- Java:装箱值和相等性
- Java:基元 vs 对象和引用
- Java:包装类型
- Java:自动装箱和拆箱
这篇关于为什么 Java 看不到整数相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!