为什么整数 ==
运算符不适用于 128 及之后的整数值?有人能解释一下这种情况吗?
这是我的 Java 环境:
java version "1.6.0_37"
Java(TM) SE Runtime Environment (build 1.6.0_37-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.12-b01, mixed mode)
示例代码:
Integer a;
Integer b;
a = 129;
b = 129;
for (int i = 0; i < 200; i++) {
a = i;
b = i;
if (a != b) {
System.out.println("Value:" + i + " - Different values");
} else {
System.out.println("Value:" + i + " - Same values");
}
}
部分控制台输出:
Value:124 - Same values
Value:125 - Same values
Value:126 - Same values
Value:127 - Same values
Value:128 - Different values
Value:129 - Different values
Value:130 - Different values
Value:131 - Different values
Value:132 - Different values
最佳答案
查看 the source code of Integer .您可以在那里看到值的缓存。
缓存仅在您使用 Integer.valueOf(int)
时发生,而不是在您使用 new Integer(int)
时发生。您使用的自动装箱使用 Integer.valueOf
。
根据JLS ,您始终可以相信,对于介于 -128 和 127 之间的值,在自动装箱后您会获得相同的 Integer 对象,并且在某些实现中,即使对于更高的值,您也可能会获得相同的对象。
实际上在 Java 7 中(我认为在 Java 6 的较新版本中),implementation IntegerCache 类的属性已经改变,上限不再是硬编码的,但它可以通过属性“java.lang.Integer.IntegerCache.high”进行配置,所以如果你使用 VM 参数 -Djava 运行程序.lang.Integer.IntegerCache.high=1000
,您会得到所有值的“相同值”。
但是 JLS 仍然保证它只到 127:
Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly.
For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.
This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all characters and shorts, as well as integers and longs in the range of -32K - +32K.
关于java - 为什么相等运算符适用于整数值直到 128 数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15024933/