Integer缓存池

通过代码说明Integer缓存池的存在:

Java中,Integer类有一个缓存池,它缓存了一定范围内的Integer对象。

可以用以下代码来验证:

public class Test01 {
    public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;
        Integer c = 128;
        Integer d = 128;
        
        System.out.println(a == b); // 输出:true
        System.out.println(c == d); // 输出:false
    }
}

根据上方所示代码的运行结果可以看出,由于127是在Integer缓存池的范围内的,所以a和b实际上指向的是同一个缓存对象,因此a == b返回true。

对于c和d,由于128超出了缓存池的范围,因此c和d是两个不同的对象,因此c == d返回false。

缓存池的定义:

缓存池的实现位于Integer类的内部类IntegerCache中,以下是有关缓存池关键代码的解析:

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

其中low和high定义了缓存池的范围,默认情况下low为-128,high为127。

cache是一个Integer数组,用于存储缓存的对象。

static代码块在类加载时执行,cache数组的大小被设置为(high -  low) + 1,按照-128到high填充Integer对象,保证这些值不会被多次创建。

最后还使用assert语句用于检查high的值至少为127。

Integer.valueOf()方法对于缓存池的意义:

Integer.valueOf(int i)方法是使用缓存池的主要方式。该方法决定了在何种情况下会复用缓存池对象。以下是该方法的源代码:

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

根据方法可以看到如果i的值在缓存池的low和high的范围内,则直接从缓存池中返回对应的Integer对象。如果i的值超出了缓存池的范围,则创建一个新的Integer对象。

因此可以得知如果在日常的使用中,在需要Integer对象时,优先使用Integer.valueOf(int i)方法,而不是直接使用new Integer(int i),因为前者可以利用缓存池达到对象复用,相同的整数值可以共享同一个Integer对象,节省了内存和提高性能。而后者总是创建一个新的对象。

总结:

Integer缓存池通过缓存一定范围内的Integer对象,减少了内存的消耗和对象的创建。通过Integer.valueOf(int i)方法,可以充分利用缓存池,提升程序的性能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值