Java: Integer equals vs. ==(Java:整数等于 vs. ==)
问题描述
从 Java 1.5 开始,您几乎可以在许多情况下将 Integer 与 int 互换.
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:整数等于 vs. ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:整数等于 vs. ==
基础教程推荐
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 将 Windows 证书导入 Java 2022-01-01
