java - 为什么相等运算符适用于整数值直到 128 数字?

标签 java integer equals-operator

为什么整数 == 运算符不适用于 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/

相关文章:

java - 检查数组列表中的空字符串

algorithm - 找到整数 N,加上它的(十进制)倒数,等于 M

c# - 将两个整数映射到一个(有上限)

c# - 重复拳击做出不同的引用?

c++ - == 和 != 运算符是编译器生成的吗?

java - 如何向类型层次结构中的类添加缺失的方法以允许统一处理?

java - 类型不匹配将 char[] 转换为对象

java - 推送通知模块发送 null

css - webkit 只是切断了 css 编号中的小数点……如何解决?

c# - 定义运算符 == 但不定义 Equals() 或 GetHashCode() 有什么问题?