IntegerCache详解

IntegerCache是Integer的内部类,用来将-128——high之间的对象进行实例化

 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;//h值,可以通过设置jdk的AutoBoxCacheMax参数调整(以下有解释),自动缓存区间设置为[-128,N]。注意区间的下界是固定 
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);// 取较大的作为上界,但又不能大于Integer的边界MAX_VALUE
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low));
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }

        private IntegerCache() {}
    }

这个主要是有自动装箱拆箱引发的问题:

引例,看如下代码 

收藏代码

 

  1. int a = 100, b = 100;  

  2. System.out.println(a == b); // true,缓存了  

  3. Integer c = 1000, d = 1000;  

  4. System.out.println(c == d); // false,没有缓存,要new  

  5. Integer e = -128, f = -128;  

  6. System.out.println(e == f); // true,缓存了  

  7. Integer g = -129, h = -129;  

  8. System.out.println(g == h); // false,没有缓存,要new 

IntegerCache 不會有实例,它是 private static class IntegerCache,在 Integer 中都是直接使用其 static 方法 …

 

Integer i = 5;//自动装箱,内部运行时,通过Integer.valueOf(5);方法将5封装成Integer对象。

这个方法主要用于提供缓存数据,提高效率,同时用于解决自动装箱问题

把先建立的Integer对象都放到这个缓存里面

 

posted on 2015-08-29 18:55  wzyxidian  阅读(1625)  评论(0编辑  收藏  举报

导航