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

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

问题描述

我有整数,应该是相等的(我通过输出验证)。但在我的 if 条件Java没有看到这些变量具有相同的值。



我有以下代码:

  if ] == point [0]&&&&&&& amp [1] == point [1]){
game.log.fine(>>>>> ;
} else {
game.log.fine(>>>>>>>不同);
}
game.log.fine(比较:+ pay [0] +,+ pay [1] + - >+ point [0] + [1]);

并产生以下输出:

  FINE:>>>>>>不同
FINE:比较:: 60,145 - > 60,145

可能要添加定义如下:

  Integer [] point = new Integer [2]; 

构造函数:

  for(Integer [] pay:payoffs2exchanges.keySet())

解决方案


因此,这两个变量都具有整数类型。 >

对象(例如 Integer s)不应该通过 == 进行比较, $ c> .equals()



重要的是要理解几个不同的 Integer 对象可以表示相同的int值。当您的程序打印>>>不同,它只是说第一个对象不是与第二个对象相同的对象。 (您可能希望根据它们表示的值来比较对象。)



关于自动装箱的正式指南


[...] ==运算符对Integer表达式执行引用标识比较和对int表达式执行值等式比较。 [...]


可能值得注意的是,自动装箱保证返回相同的对象为整数值范围[-128,127],但实现可以自行决定是否缓存该范围之外的值。



我的一般建议是使用 int ,而不是所有本地/成员变量的 Integer 。在这种特殊情况下,您似乎将坐标存储在2元素数组中。我建议您将它封装在 Coordinates 类或类似类中,并覆盖此处的equals方法(和hashCode)。



另请参阅




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.

解决方案

Objects (such as Integers) should not be compared through ==, but through .equals().

What's important to understand is that several different Integer objects can represent the same int value. When your program prints >>> different it simply says that the first object is not the same object as the second object. (While you probably want to compare the objects based on which value they represent.)

From the official guide on autoboxing:

[...] The == operator performs reference identity comparisons on Integer expressions and value equality comparisons on int expressions. [...]

It may be worth noting that autoboxing is guaranteed to return the same object for integral values in the range [-128, 127], but an implementation may, at its discretion, cache values outside of that range.

My general recommendation is to use int instead of Integer for all local / member variables. In this particular case you seem to store coordinates in a 2-element array. I would suggest that you encapsulate this in a Coordinates class or similar and override the equals method (and hashCode) in here.

See also

这篇关于为什么Java看不到整数是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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