Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?(为什么在比较 Java 中的整数包装器时 128==128 为假但 127==127 为真?)
问题描述
class D {
public static void main(String args[]) {
Integer b2=128;
Integer b3=128;
System.out.println(b2==b3);
}
}
输出:
false
<小时>
class D {
public static void main(String args[]) {
Integer b2=127;
Integer b3=127;
System.out.println(b2==b3);
}
}
输出:
true
注意:-128 到 127 之间的数字为真.
Note: Numbers between -128 and 127 are true.
推荐答案
当您在 Java 中编译数字文字并将其分配给整数(大写 I
)时,编译器会发出:
When you compile a number literal in Java and assign it to a Integer (capital I
) the compiler emits:
Integer b2 =Integer.valueOf(127)
这行代码也是在你使用自动装箱的时候生成的.
This line of code is also generated when you use autoboxing.
valueOf
的实现使得某些数字被池化",它为小于 128 的值返回相同的实例.
valueOf
is implemented such that certain numbers are "pooled", and it returns the same instance for values smaller than 128.
来自 java 1.6 源代码,第 621 行:
From the java 1.6 source code, line 621:
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
high
的值可以通过系统属性配置为另一个值.
The value of high
can be configured to another value, with the system property.
-Djava.lang.Integer.IntegerCache.high=999
-Djava.lang.Integer.IntegerCache.high=999
如果您使用该系统属性运行程序,它将输出 true!
If you run your program with that system property, it will output true!
显而易见的结论:永远不要依赖两个引用是相同的,总是用 .equals()
方法比较它们.
The obvious conclusion: never rely on two references being identical, always compare them with .equals()
method.
所以 b2.equals(b3)
将为 b2,b3 的所有逻辑相等值打印 true.
So b2.equals(b3)
will print true for all logically equal values of b2,b3.
请注意,Integer
缓存不是出于性能原因,而是为了符合 JLS,第 5.1.7 节;必须为值 -128 到 127(含)提供对象标识.
Note that Integer
cache is not there for performance reasons, but rather to conform to the JLS, section 5.1.7; object identity must be given for values -128 to 127 inclusive.
Integer#valueOf(int) 也记录了这种行为:
通过缓存频繁请求的值,此方法可能会显着提高空间和时间性能.此方法将始终缓存 -128 到 127(含)范围内的值,并可能缓存此范围之外的其他值.
this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
这篇关于为什么在比较 Java 中的整数包装器时 128==128 为假但 127==127 为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在比较 Java 中的整数包装器时 128==128 为假但 127==127 为真?


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01