说说Integer、Long等包装类的缓存机制

本文详细介绍了Java中Integer等包装类的静态代码块初始化缓存机制,尤其是Integer类如何通过IntegerCache进行缓存。在-128到127之间的Integer对象会使用缓存,超出此范围则新建对象。此外,还探讨了valueOf方法在自动装箱过程中的作用。通过对IntegerCache源码的分析,展示了如何通过系统属性设置缓存的最大值。
摘要由CSDN通过智能技术生成

分析&回答


包装类:Byte,Short,Integer,Long,Character

他们使用static代码块进行初始化缓存,其中Integer的最大值可以通过high设置;Boolean使用static final实例化的对象;Float和Double直接new的对象没有使用缓存。

Integer举例如下:

Integer a = 127;
Integer b = 127;
log.info("S:{}",a == b );

Integer c = 128;
Integer d = 128;
log.info("X:{}",c == d );

输出
S:true
X:false

默认范围:在-128到127之间使用自动装箱时,会使用缓存。范围的最大值可以通过java.lang.Integer.IntegerCache.high设置,通过for循环将范围内的数据实例化为Integer对象放到cache数组里,如下面代码:

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() {}
}

反思&扩展


使用自动装箱将基本类型转为封装类对象这个过程其实底层实现是调用封装类的valueOf方法:

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

喵呜面试助手: 一站式解决面试问题,你可以搜索微信小程序 [喵呜面试助手] 或关注 [喵呜刷题] -> 面试助手 免费刷题。如有好的面试知识或技巧期待您的共享!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵呜刷题

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值