为什么 Integer a = 100, b = 100 时 a == b为 true,但改成 200 就变成 false?背后的机制是什么?

验证

运行代码

java 复制代码
public class Main{
    public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;
        System.out.println(a == b);
        Integer c = 200;
        Integer d = 200;
        System.out.println(c == d);
    }
}

运行结果

out 复制代码
true
false

原因

java 复制代码
Integer a = 100;

这段代码是自动装箱/拆箱机制,本质上是调用Integer.valueof(100)

给出源码

java 复制代码
@IntrinsicCandidate
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

可以看到当i的值在IntegerCache.low到IntegerCache.high之间的时候返回缓存池里面的值,否则返回新值,我们再具体看一下IntegerCache的源码。

java 复制代码
private static final class IntegerCache {
    static final int low = -128;
    static final int high;

    @Stable
    static final Integer[] cache;
    static Integer[] archivedCache;

    static {
        int h = 127;
        String integerCacheHighPropValue =
            VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                h = Math.max(parseInt(integerCacheHighPropValue), 127);
                h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
            }
        }
        high = h;
        CDS.initializeFromArchive(IntegerCache.class);
        int size = (high - low) + 1;
        if (archivedCache == null || size > archivedCache.length) {
            Integer[] c = new Integer[size];
            int j = low;
            int archivedSize = (archivedCache == null) ? 0 : archivedCache.length;
            for (int i = 0; i < archivedSize; i++) {
                c[i] = archivedCache[i];
                assert j == archivedCache[i];
                j++;
            }
            for (int i = archivedSize; i < size; i++) {
                c[i] = new Integer(j++);
            }
            archivedCache = c;
        }
        cache = archivedCache;
        assert IntegerCache.high >= 127;
    }
    private IntegerCache() {}
}

也就是说如果数值在[-128,127]之间,就返回缓存池里面已经存在的对象,否则创建一个新的Integer对象。

上面代码,a和b都是100,在[-128,127]之间,都是缓存池里面的同一个对象,指向同一地址,c和d是200,不在[-128,127]之间,会返回新的,指向不同地址。

面试

在 Java 中,Integer 对象的比较行为受缓存机制影响。对于值在 [-128, 127] 范围内的 Integer,由于缓存池的存在,多个 Integer 实例会指向同一个对象,导致 == 比较为 true。而超出此范围的 Integer 则会返回新的对象,因此 == 比较为 false

相关推荐
是娇娇公主~3 分钟前
C++ 中 std::deque 的原理?它内部是如何实现的?
开发语言·c++·stl
SuperEugene22 分钟前
Axios 接口请求规范实战:请求参数 / 响应处理 / 异常兜底,避坑中后台 API 调用混乱|API 与异步请求规范篇
开发语言·前端·javascript·vue.js·前端框架·axios
xuxie991 小时前
N11 ARM-irq
java·开发语言
cjy0001111 小时前
springboot的 nacos 配置获取不到导致启动失败及日志不输出问题
java·spring boot·后端
wefly20172 小时前
从使用到原理,深度解析m3u8live.cn—— 基于 HLS.js 的 M3U8 在线播放器实现
java·开发语言·前端·javascript·ecmascript·php·m3u8
zhenxin01222 小时前
Spring Boot实现定时任务
java
小江的记录本2 小时前
【事务】Spring Framework核心——事务管理:ACID特性、隔离级别、传播行为、@Transactional底层原理、失效场景
java·数据库·分布式·后端·sql·spring·面试
sheji34162 小时前
【开题答辩全过程】以 基于springboot的校园失物招领系统为例,包含答辩的问题和答案
java·spring boot·后端
luanma1509802 小时前
PHP vs C++:编程语言终极对决
开发语言·c++·php
寂静or沉默2 小时前
2026最新Java岗位从P5-P7的成长面试进阶资源分享!
java·开发语言·面试