我有应该相等的整数(我通过输出验证它).但是在我的 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、Longs 或 Booleans 比较包装器类型时code>!=,您将将它们作为参考进行比较,而不是作为值进行比较.
When comparing wrapper types such as Integers, Longs or Booleans 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 看不到整数相等?
发布评论