Integer 中的缓存类IntegerCache

来源:互联网 发布:网络安全产品排行 编辑:程序博客网 时间:2024/04/29 20:10

Cache为[-128,127],IntegerCache有一个静态的Integer数组,在类加载时就将-128 到 127 的Integer对象创建了,并保存在cache数组中,一旦程序调用valueOf 方法,如果取的值是在-128 到 127 之间就直接在cache缓存数组中去取Integer对象,超出范围就new一个对象。

 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) {                int i = parseInt(integerCacheHighPropValue);                i = Math.max(i, 127);                // 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() {}    }

                Integer i = 127;Integer j = 127;System.out.println(i==j);//trueInteger i1 = 128;Integer j1 = 128;System.out.println(i1==j1);//falseInteger i2 = new Integer(127);Integer j2= new Integer(127);System.out.println(i2==j2);//falseSystem.out.println(200 == i); //false






0 0
原创粉丝点击