Java Integer之“==”问题

有趣的一个Java基础类的问题。

Integer a = 100;
Integer b = 100;
System.out.println(a == b); 

Integer c = 1000;
Integer d = 1000;
System.out.println(c == d);

输出分别为true,false.
“==”我们都知道是引用目标地址的判断是否相等。因此上述应该都是false才对的。但是为什么会出现这种情况了,去Integer.java源码看下就知道了。

在Integer.java中,发现了其有一个内部类IntegerCache,这个类的作用就是用来缓存-127~128的整数的,所以任何在-127~128之间的两个数值相等的整数以“==”比较都是true。相当于调用了Integer.valueof(int i)的方法

a = Integer.valueof(100);
b = Integer.valueof(100);

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

IntegerCache的源码:

 /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

参考:https://dzone.com/articles/why-1000-1000-retyrns-false-but-100-100-returns-true

### Java 中 `Integer` 类型的等于比较 在 Java 中,对于 `Integer` 对象使用 `==` 和 `equals()` 方法进行比较会得到不同的结果。具体来说: - 当使用 `==` 比较两个 `Integer` 对象时,实际上是在比较它们的内存地址而非实际数值。这意味着即使两个不同对象包含相同的整数值,只要它们不是同一个实例,`==` 将返回 `false`[^2]。 例如: ```java Integer c = 128; Integer d = 128; System.out.println(c == d); // 输出: false ``` 然而,由于 JVM 的优化机制——自动装箱缓存(Autoboxing Cache),当 `Integer` 值位于 `-128` 至 `127` 范围内时,JVM 会对这些值进行缓存处理,使得相同范围内的 `Integer` 实例共享同一份内存空间。因此在这个范围内使用 `==` 可能会出现意外的结果。 而 `equals()` 方法则是用来比较两个 `Integer` 对象的实际数值是否相等。无论 `Integer` 是否超出上述提到的缓存区间,`equals()` 总是比较其内部存储的具体数值而不是引用本身[^3]。 下面是一个完整的例子展示两者的差异: ```java public class Main { public static void main(String[] args) { Integer a = new Integer(10); Integer b = new Integer(10); System.out.println(a == b); // 输出: false (因为a和b是两个独立的对象) System.out.println(a.equals(b)); // 输出: true (因为两者表示相同的数值) Integer e = 127; Integer f = 127; System.out.println(e == f); // 输出: true (得益于自动装箱缓存) System.out.println(e.equals(f)); // 输出: true Integer g = 128; Integer h = 128; System.out.println(g == h); // 输出: false (超过缓存范围) System.out.println(g.equals(h)); // 输出: true } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值