Java 基础数据类型包装类的高频区间的数据缓存

Java的基础数据类型包装类中,除了Double和Float,其他如Integer、Byte、Short、Character都有高频缓存区间。这个缓存区间对于-128到127的Integer、-128到127的Byte、-128到127的Short、0到127的Character,会复用对象。超出此范围则在堆上创建新对象。在比较时,推荐使用equals而非"=="。Integer类可以通过VM参数调整缓存最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Java的基础数据类型的包装类:Integer,Long,Double,Float,Boolean,Byte,Short,Character。

二、高频缓存区

  • 其中Double和Float没有缓存,其他类型都有高频缓存区间。其高频缓存区间的缓存范围是:
    Boolean:使用静态final,就会返回静态值
    Byte:-128~127
    Short:-128~127
    Character:0~127
    Long:-128~127
    Integer:-128~127

  • 如果所使用的包装类的值在这个缓存区间内,就会直接复用已有对象,在缓存区间之外的数值会重新在堆上产生。所以在判断是否相等时不要用“==”,用equals,否则会出现以下情况:
    Integer i1 = 127;
    Integer i2 = 127;
    i1 == i2 ->true

    Integer i3 = 128;
    Integer i4 = 128;
    i3 == i4 ->false
  • Integer是唯一一个可以修改缓存范围的包装类。在VM options加入参数: -XX:AutoBoxCacheMax=555即将缓存区间的最大值改为555.   (以上内容属于转载 https://blog.51cto.com/14305934/2432216 以下为扩充)
  •   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() {}
        }

    根据查看 IntegerCache源码可知设置只能扩大缓存区不能缩小

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值