Java:整数等于 vs. ==

从 Java 1.5 开始,您几乎可以在许多情况下将 Integerint 互换.

As of Java 1.5, you can pretty much interchange Integer with int in many situations.

但是,我发现我的代码中有一个潜在的缺陷,这让我有点吃惊.

However, I found a potential defect in my code that surprised me a bit.

以下代码:

Integer cdiCt = ...;
Integer cdsCt = ...;
...
if (cdiCt != null && cdsCt != null && cdiCt != cdsCt)
    mismatch = true;

当值相等时,似乎错误地设置了不匹配,尽管我无法确定在什么情况下.我在 Eclipse 中设置了一个断点,发现 Integer 的值都是 137,我检查了布尔表达式,它说它是假的,但是当我越过它时,它将不匹配设置为真.

appeared to be incorrectly setting mismatch when the values were equal, although I can't determine under what circumstances. I set a breakpoint in Eclipse and saw that the Integer values were both 137, and I inspected the boolean expression and it said it was false, but when I stepped over it, it was setting mismatch to true.

将条件更改为:

if (cdiCt != null && cdsCt != null && !cdiCt.equals(cdsCt))

解决了问题.

谁能解释一下为什么会这样?到目前为止,我只在我自己的 PC 上的本地主机上看到了这种行为.在这种特殊情况下,代码成功通过了大约 20 次比较,但在 2 次比较失败.问题始终可以重现.

Can anyone shed some light on why this happened? So far, I have only seen the behavior on my localhost on my own PC. In this particular case, the code successfully made it past about 20 comparisons, but failed on 2. The problem was consistently reproducible.

如果这是一个普遍存在的问题,它应该会导致我们的其他环境(开发和测试)出现错误,但到目前为止,在执行此代码片段的数百次测试之后,没有人报告此问题.

If it is a prevalent problem, it should be causing errors on our other environments (dev and test), but so far, no one has reported the problem after hundreds of tests executing this code snippet.

使用 == 比较两个 Integer 值仍然不合法吗?

Is it still not legitimate to use == to compare two Integer values?

除了下面所有的好答案之外,下面的 stackoverflow 链接还有很多额外的信息.它实际上会回答我原来的问题,但是因为我没有在我的问题中提到自动装箱,所以它没有出现在选定的建议中:

In addition to all the fine answers below, the following stackoverflow link has quite a bit of additional information. It actually would have answered my original question, but because I didn't mention autoboxing in my question, it didn't show up in the selected suggestions:

为什么编译器/JVM就不能让自动装箱正常工作"?

推荐答案

JVM 正在缓存整数值.因此,与 == 的比较仅适用于 -128 到 127 之间的数字.

The JVM is caching Integer values. Hence the comparison with == only works for numbers between -128 and 127.

参考:#Immutable_Objects_.2F_Wrapper_Class_Caching

相关文章