Java:整数等于与 == [英] Java: Integer equals vs. ==

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

问题描述

从 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

这篇关于Java:整数等于与 ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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