问题描述
可能的重复:
奇怪的 Java 拳击
最近在我阅读有关包装类的文章时,我遇到了一个奇怪的案例:
Recently while I was reading about wrapper classes I came through this strange case:
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1 == i2) System.out.println("same object");
打印:
different objects
和
Integer i1 = 10;
Integer i2 = 10;
if(i1 != i2) System.out.println("different objects");
if(i1 == i2) System.out.println("same object");
打印:
same object
对于这种情况有什么合理的解释吗?
Is there any reasonable explanation for this case?
谢谢
推荐答案
对于第二种情况 ==
返回 true 的原因是因为包装器装箱的原始值足够小,可以被实习到运行时相同的值.因此它们是相等的.
The reason why ==
returns true for the second case is because the primitive values boxed by the wrappers are sufficiently small to be interned to the same value at runtime. Therefore they're equal.
在第一种情况下,Java 的整数缓存不足以容纳数字 1000,因此您最终创建了两个不同的包装器对象,通过引用比较它们返回 false.
In the first case, Java's integer cache is not large enough to contain the number 1000, so you end up creating two distinct wrapper objects, comparing which by reference returns false.
上述缓存的使用可以在Integer#valueOf(int)
方法中找到(其中IntegerCache.high
默认为127):
The use of said cache can be found in the Integer#valueOf(int)
method (where IntegerCache.high
defaults to 127):
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
正如 Amber 所说,如果你使用 .equals()
那么这两种情况总是会返回 true,因为它会在必要时将它们拆箱,然后比较它们的原始值.
As Amber says, if you use .equals()
then both cases will invariably return true because it unboxes them where necessary, then compares their primitive values.
这篇关于使用 == 和 != 的奇怪包装类行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!