Why is == true for some Integer objects?(为什么 == 对于某些 Integer 对象为真?)
问题描述
可能重复:
整数包装器对象仅共享相同的实例在值 127 以内?
我从 Khalid Mughal SCJP 复制了以下程序片段,但我无法
理解输出.
I have copied the following program snippet from the Khalid Mughal SCJP, but I am unable to
understand the output.
public class RQ200_60 {
public static void main(String[] args) {
Integer i = -10;
Integer j = -10;
System.out.print(i==j); // output: true -- why true?
System.out.print(i.equals(j)); // output: true
Integer n = 128;
Integer m = 128;
System.out.print(n==m); // output: false
System.out.print(n.equals(m)); // output: true
}
}
上面的程序为第一个打印语句给出了输出 true,但它应该给出 false,因为它是与 == 关系运算符的引用比较.但是第三次打印给出了错误,我不明白这种不一致.
The above program giving output true for the first print statement but it supposed to give false because it is reference comparison with == relational operator. But third print gives false and I don't understand this inconsistency.
非常感谢您的解释!
推荐答案
在第一种情况下,对象 i
和 j
都指向同一个缓存对象.默认情况下,-128 到 127 之间的范围被缓存为 Integer
对象.我们可以使用 JVM arguments
In the first case, both the objects i
and j
are pointing to the same cached object. By default, the range between -128 and 127 are cached as Integer
Object. We can increase the range using JVM arguments
这篇关于为什么 == 对于某些 Integer 对象为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 == 对于某些 Integer 对象为真?


- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01