【学习笔记】Java整形缓存机制(integer)

最常见的Integer用法: 

Integer i = Integer.valueOf(10);

在下面的比较中:

Integer i = Integer.valueOf(10);
Integer j = 10;
Integer k = new Integer(10);

System.out.println(j == i);  // true
System.out.println(j == k);  // false

从运行结果中可以知道,Integer.valueOf() 并没有创建新的对象。

从源码中去探索:

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

IntegerCache.low代表integer缓存最小值,IntegerCache.high代表integer缓存最大值,return之前做了一个判断,判断传进来的值是否是在两值之间。

在往深一层:

    private static class IntegerCache {
        static final int low = -128;  // 缓存最小值
        static final int high;        // 缓存最大值(没有默认值,可自定义,上限是2的31次方-1)
        static final Integer cache[]; // 缓存值数组

        static {
            // high value may be configured by property
            int h = 127; // 缓存最大值默认是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() {}
    }

判断如果在最大最小值之前则直接取缓存数组对应下标的值,注意数组下标要加128,因为从-128开始创建对象。

既然默认值是从-128到127,那么再回到开始:

Integer i = Integer.valueOf(1000);
Integer j = 1000;

System.out.println(j == i);  // false

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

MichelleChung

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

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

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

打赏作者

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

抵扣说明:

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

余额充值