为什么 Java 看不到整数相等? [英] Why Java does not see that Integers are equal?

查看:34
本文介绍了为什么 Java 看不到整数相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有应该相等的整数(我通过输出验证它).但是在我的 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


参考资料/进一步阅读

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆